2. CSS
Table of Contents
Key Concepts
CSS (Cascading Style Sheets) defines the appearance of HTML documents: colors, typography, spacing, and layout.
CSS syntax consists of selectors, properties, and values. Each
property: value;pair is called a declaration.CSS can be added via internal
<style>tags, inlinestyleattributes, or external.cssfiles. External stylesheets are the best practice as they promote reusability and separation of concerns.Selectors target elements to style:
Element selector:
p { }— targets all<p>elementsClass selector:
.intro { }— targets elements withclass="intro"ID selector:
#main { }— targets the element withid="main"Multi-selector:
h1, h2, h3 { }— targets multiple element typesPseudo-class selector:
a:hover { }— targets elements in a specific state
Specificity determines which styles win when multiple rules apply: ID > Class > Element. If specificity is equal, the last rule wins.
Units: Use
remfor font sizes (accessible, scales with user settings),%for relative sizing, and avoidpxfor font sizes.
Intro to CSS
In the previous lesson, we learned how to structure content with HTML. Now we'll transform the appearance of our pages with CSS.
When the world wide web was born, it was just a means of communicating information. The world of design hadn't yet made its way to the internet and websites looked like this:

As you can see, the browser already has some default styles applied to elements of different types. Headings are bigger and bolder than paragraphs. Hyperlinks ("anchors") are blue and underlined.
But with CSS, we can override those defaults and dramatically transform the page.

Which website would you rather use? Which one feels more trustworthy and professional? CSS bridges the gap between content and experience. As a developer, understanding CSS allows you to:
Control visual hierarchy
Guide users' attention to what's important
Create responsive layouts
Make your app usable on phones, tablets, and desktops
Implement design systems
Build consistent, professional interfaces
Debug styling issues
Fix layout problems that break user experience
Later, when you learn DOM manipulation with JavaScript, you'll be able to dynamically change CSS in response to user actions—highlighting selected items, showing/hiding elements, animating transitions, and more. A solid CSS foundation makes that JavaScript work much more powerful.
CSS Syntax
CSS is written using selectors, properties, and values:
Selectors (like
body,figure, andimg) specify which HTML element(s) to style. Selectors are followed by curly braces{}which contain the properties for the selected element(s).Properties (like
background,color,max-width, etc.) tell our browser which aspect of the element to change.Each property has a set of valid values that can be assigned to them (like
azureormidnightbluefor colors,centerfor alignment, and300pxor100%for sizing and spacing.)
Each property: value; pair is called a declaration that must be followed by a semicolon.
Now, let's see where we can put this CSS code.
Linking/Loading CSS Files
There are three ways to add CSS to an HTML document:
Inside a separate
.cssfile, loaded via a<link>tag (best practice)Inside
<style></style>tags (okay for small projects)As attributes of individual elements (don't do this)
External Stylesheets (Best Practice)
CSS is most commonly written in separate .css files that are loaded by an HTML file via the <link> element.
The
rel(relationship) attribute tells the browser what kind of file is being linked (other file types can also be loaded using this tag)The
href(hyperlink reference) attribute is an absolute/relative path to the.cssfile
Then, in style.css, we can add some CSS selectors and declarations:
TODO: Add the CSS above into style.css and load it into your HTML file using the link tag. Then, copy that link tag into your contact.html and portfolio.html pages.
Internal Stylesheets With Style Tags (Fine If You Only Want 1 File)
In the index.html file and add these <style> tags and CSS within the <head>:
Note that the order of our external/internal stylesheets matters. See what happens if you put the external stylesheet after the internal one. The stylesheet that we add last will always "win out". This is what the "cascading" part of "Cascading Style Sheets" refers to.
This approach is appropriate under two circumstances:
if you want to have styles for a particular page override the external stylesheet
if you want to keep all of your code inside of one file and not use an external stylesheet at all
Inline Styling (Practically Never Do This)
You can also add a style attribute directly to an individual element but this should only be done for testing purposes:
Inline styles are not a viable option for large scale styling. However, inline styles will always override both internal and external stylesheets. Therefore, it might be useful if you need to quickly test a CSS property and ensure that it will be applied to an element.
But generally you should avoid this approach.
Inspecting CSS With Chrome Developer Tools
You can see how competing styles override each other if you open the Chrome Developer Tools and look at the styles applied to the body element

Notice how the styles "cascade" in the following manner:
The inline
element.styleproperties appear at the top and override all other stylesNext are the internal stylesheet styles from
index.htmlThird are the external stylesheet styles from
style.cssLast are the user agent stylesheet styles. These are the default styles applied by the browser.
The Chrome Developer Tools are incredibly useful for testing out your CSS styling. For example:
Try disabling the inline
backgroundapplied to the body and notice how the page will update immediately to use the next background color in the "cascade".Click on the named color
redand type ingreento see the color changeClick on the color box and play around with the sliders to find a color that you like for the background.
TODO: Remove all inline styles and the internal stylesheet. We'll use the external stylesheet style.css moving forward.
Common CSS Properties
Now that we know how to add CSS to our HTML files, let's learn the basic CSS properties that we can apply to any HTML element.
Color Properties
One of the most obvious uses of CSS is to apply color to our otherwise black and white webpages.
In addition to beautifying our page, colors can make a page easier to navigate by visually distinguishing sections from each other.
We will most commonly be setting the background color and text color of our elements:
Color values can be written in a variety of ways. For example, these are all equivalent ways to use the color blue:
Named color:
blueRed/Green/Blue (RGB):
rgb(0, 0, 255)Each value ranges from 0 to 255
Hex code:
#0000ffEach pair of base-16 values range from
00(0) toff(255) and represent red/green/blue.
Typography Properties
Your choice of font can add a nice touch of personality to a website. How you configure your typography can also make a big difference in the readability of your site.
Fun fonts can be downloaded from the internet (check out Google Fonts) but classic fonts like Helvetica and Arial will never let you down:
Again, we can set these properties in the body and they will be inherited by all descendent elements.
Here are a few notes to consider for each of these properties
font-family: List multiple fonts separated by commas. The browser uses the first available font. Always end with a generic family likesans-seriforserifas a fallback.line-height: A line height between1.4and1.6improves readability. Use unitless numbers (e.g.,1.5) so the line height scales with the font size.text-align: Useleftfor natural reading flow in most languages, butcentercan help for headings or to create visual emphasis. Avoid centering long paragraphs for readability.font-size: Use relative units likereminstead ofpxto ensure that your font responds to each device's base font size. For example,1remis equivalent to16pxfor devices with "normal" text,12pxfor "small" text, and24pxfor "large" text.
TODO: Set the text alignment for the ol element to left
Selectors
There are TONS of ways to select elements with CSS rules (list of all the selectors).
The most common selectors are:
By element (select all
lielements)By class name (select all elements with
class="blue")By id name (select the element with
id="email-form")Or some combination of these things
TODO: For each of the examples below, try adding them to your style.css file!
Element Selector
We've already been using this selector type to target all elements of a specific type:
Class Selector
A class attribute can be added to elements in order to style them as a group.
HTML:
To target those elements, use a dot (.) followed by the class name:
CSS:
Rules for classes:
Multiple elements can share the same class.
Names are case-sensitive
Cannot start with numbers
Cannot contain spaces
Use
kebab-casefor multi-word names (e.g.,programming-skill)
TODO: Add a "quote" class to all of your quote list items and give them a background color of powderblue and a text color of midnightblue.
ID Selector
When we want to target a single element, we can add an id attribute in the HTML to label it
HTML:
Then, to style that one element and no others, we write the name of the id with a hash (#):
CSS:
Remember, each id should be unique on the page. If you want to style multiple elements the same way, use a class instead.
Special Selectors
Multi-Selectors
You can apply the same styles to multiple selectors by separating them with a comma (,):
TODO: Use the multi-selector syntax to set text-align: left; for these elements: h3, ul, and ol.
Child Selectors
Currently, the hyperlink <a> in the footer has the same styles as the navigation links in the header but we only want those styles to apply to the hyperlinks in the header.
You can select elements that are direct descendants of other elements using the right angle bracket parent>child syntax.
Modify the a selector to use the child selector syntax
Pseudo-Class Selectors
Pseudo-class selectors let us select an element in a particular state such as when it is being hovered:
Add this style just below the nav>a selector.
Selector Specificity
When multiple CSS rules apply to the same element, the browser follows these rules to determine which styles win:
Specificity: More specific selectors override less specific ones
ID selectors (
#main-title) are most specificClass selectors (
.intro) are less specificElement selectors (
p) are least specific
Source order: If specificity is equal, the rule that appears last wins
Example:
Choosing a Color Palette and Custom Variables
When designing a website, it is best to decide on a color palette with just a few colors to stick to. Here is a useful strategy to create a simple palette:
Choose one primary color to define your entire palette (e.g.
powderblue)Choose a second color that has high-contrast with the first (e.g.
midnightblue)Choose a third "accent" color that you can use for call-to-action elements like buttons and forms (e.g.
royalblue)Don't shy away from using white and black when needed!
To make it easier to stick to a particular palette, it can be incredibly useful to define CSS Variables for your colors.
These variables, which must begin with --, can be defined within any selector. However, those variables will only be available within the "scope" of that element.
So, it is most common to define them in :root which is a special selector that grabs the top-most element of a document (the html element). As a result, the variables are globally available.
We can then update our CSS to use those variables using the var() property value function:
TODO: Decide on a three- or four-color palette and then define variables for your colors using the :root selector. Then, update your code to use those variables.
Deep Dive On Units: px vs % vs rems
px vs % vs remsThe
pxunit sets the exact size of a property. Setting the size of an element usingpxvalues should be avoided if possible as they don't comply with accessibility standards.
The
remunit sets a size of an element relative to the browser's base font size which is typically16pxby default. Users can change their base font size as an accessibility feature. If your website usesremunits instead ofpx, your font will scale according to your user's accessibility settings.
The percentage
%unit will set the size of an element to a percentage of its parent element's width. So, if you have a parent element with a width of100px, and the child has its width set to75%, the child will have a width of75px. Use this carefully!
Quiz!
Q: The tags h1, h2, and p all have different default styles. How are they different?
Q: What is wrong with the CSS syntax below?
Q: For the HTML below, how would you make all p tags blue? How would you make only the p tags with class="fun" green? How would you make the second p tag orange?
Q: For the HTML and CSS below, what will be the color of paragraph? (pay close attention)
HTML:
CSS:
Q: How do you link an external CSS file called style.css to an HTML document? Where in the HTML should this go?
Q: How would you apply the same styles to all h1, h2, AND h3 elements using a single CSS rule?
Q: What are three different ways you could set an element's text color to red in CSS?
Complete CSS
Last updated