Cascading Style Sheets

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 60

Cascading Style Sheets (CSS)

Tree structures. It's not immediately obvious, but the HTML code for your web page has a
branching hierarchy or tree structure. Understanding this structure will help you apply style to
your page more effectively and efficiently.

Using CSS and HTML together. HTML and CSS are different languages, but we'll learn how to
use them together. We'll actually learn three different ways to integrate CSS with the HTML of
your web page.

But also separating them. Although they work closely together, we'll also learn how to separate
our CSS, which defines the style of the page, from the HTML, which defines the structure.
This separation of concerns will make our web development far more efficient.

A whole lot of style properties. We'll learn how improve the look of our HTML pages with CSS
style properties—from changing the color of your text to completely changing the layout.

This lesson is definitely more challenging than the last, but we hope you'll stick with it because
the payoff is well worth the work! You'll be tackling some pretty sophisticated concepts that will
dramatically improve your coding abilities. Not only will you learn far more powerful ways to
improve your web pages, but at the same time you'll also be stretching your knowledge of
computer language syntax. You'll get a better understanding of how computer languages are put
together, and that will serve you well throughout your journey as a developer.

How to Access Developer Tools in Your browser

The browser shown in the video is Google Chrome, which is what we recommend—but most
modern browsers have developer tools that work similarly. Here are instructions for a few
different browsers:

Google Chrome

Open the Chrome menu at the top right of the browser window (the three vertical dots) and
select Tools > Developer Tools.

You can also simply right-click on any page element and select Inspect.

Safari

From the menu bar, select Safari > Preferences, and click Advanced.

At the bottom of the box, check the "Show Develop menu in menu bar" checkbox.

Choose Develop > Show Web Inspector.

Mozilla Firefox
From the menu bar, select Tools > Web Developer > Inspector.

You can also simply right-click on any page element and select Inspect.

Collapsing / Expanding Elements in Developer Tools

Note that developer tools will often collapse elements, so you may need to expand them to see
what other elements are nested inside.

For example, in the animated gif below, we can see that Chrome developer tools has collapsed
the head element and it looks like this page doesn't have much HTML on it—but if we expand
the head by clicking on the little triangle dropdown, there are a bunch of other elements nested
inside:

Example HTML and CSS

Here's the HTML and CSS for the example shown in the middle of this video:

<!DOCTYPE html>

<html>

<head>

<title>Listy list</title>

<style>

p { color: red; }

ol { display: flex; }
li { margin: 20px; }

</style>

</head>

<body>

<p>These are some red red words.</p>

<ol>

<li>Apple apple berry berry sauce sauce sauce.<br>

Cook it on the stove and serve it to your boss.

<li>Betty bought a bit of butter,

but the butter's burning bitter.<br>

<li>Crisp cookies claim Charlie's cookout crown.<br> Clever Clara

clocked the crows at <em>c</em> (clearly connivance!)

<li>Daring drivers drove down Devil's Ditch in Dodges.

<li>Evil eggs explode everywhere. Eww!

</ol>

</body>

</html>

Trees to Boxes

Note that when we only have one property, the semicolon is optional—we can either include it
or not and it won't make a difference. In other words, we can do this:

<p style="color: blue;">Hello world!</p>

Or this:

<p style="color: blue">Hello world!</p>


And it will work the same. It's only when we have more than one that we must include a
semicolon to separate each of them:

<p style="color: blue; text-align: center">Hello world!</p>

If we left out the semicolon at the end of blue;, this line would not work correctly:

<p style="color: blue text-align: center">Hello world!</p>

If you try this in the workspace, you'll see that neither of these styles get applied (the text will be
neither blue nor centered). So if you find that your styles are not showing up, check for small
syntax errors—like a missing semicolon!

color: blue

And how to center the text:

text-align: center

But what if you wanted to do both of these things at the same time? This turns out to be pretty
easy. All you have to do is put one after the next—and use a semicolon ; to indicate where one
ends and the next begins:

<p style="color: blue; text-align: center;">Hello world!</p>

When we use the style attribute to create an inline style, you may have noticed that we use
quotes:

<p style="color:blue; text-align:center;">Hello!</p>

In fact, we seem to be using quotes whenever we have an attribute value (remember, the
attribute value is the part that comes after the = sign). For example, when we make a link, we put
quotes around the value of the href attribute:

<a href="https://www.udacity.com">Udacity</a>

So what's up with putting quotes around attribute values? Do we have to do this? Let's play with
it and see what we can find out.

In the workspace below, try deleting the quotes and see what happens—then answer the
questions that come after the workspace.
Note: Some of the quizzes ask you to check whether the text is blue. If you have trouble seeing
the blue color, don't worry—you can answer the questions by checking whether the text is
centered on the page.

<style>

p { font-size: 24pt; }

</style>

<p>I <em style="color: red;">love</em> CSS!</p>

Another approach that would work here is to just place both of them inside the style element:

<style>

p { font-size: 24pt; }

em { color: red; }

</style>

<p>I <em>love</em> CSS!</p>

CSS Syntax

CSS Rulesets

A CSS ruleset is made up of a selector and a declaration block.

Selectors

Selectors indicate which HTML elements the ruleset will apply to. For example, consider this
ruleset:

li {

color: green;
}

In this example, li is the selector—meaning that whatever we put between the curly
braces { } will be applied to all list item li elements on the page.

Declaration Blocks

A declaration block describes how the ruleset will modify the elements. In the above example,
the declaration block is saying that all li elements will be modified by changing their font colors
to green.

A declaration block can have multiple declarations inside of it. For example, consider this
ruleset:

p{

background-color: blue;

font-size: 20px;

The declaration block is everything other than the selecter p:

background-color: blue;

font-size: 20px;

And this declaration block contains two individual declarations. One is:

background-color: blue;

And the other is

font-size: 20px;

Properties and Values

You can break the syntax of a declaration down even further. A declaration is made up of
a property and a value. For example, in this declaration…

background-color: blue;

…the property would be background-color and the value would be blue.


CSS Selectors

CSS selector. Tell the browser which elements the rule will affect.

CSS Selectors: Type

One example of a type of CSS selector is called type. If you want to use type selector to
style all h1 elements, this is how you would write your CSS:

h1 {

font-family: serif;

CSS Selectors: Class and ID

The distinction between a class and an ID can be a bit confusing, so let's review them both.

Class

A class is a group of things with the same characteristics. To create a class, you need to use the
attribute "class" in the HTML opening tag. Then in your CSS, you use the same name you gave
the class attribute in your HTML, except you place a . in front of it.

Example:

//HTML

<div class="container">

<p> I'm inside a container! </p>

</div>

//CSS

.container {

border: 1px solid black;

In this example, the class name is container. Any element with the class attribute container will
receive the styling of border: 1px solid black;. So for example, if you added class="container"to
the paragraph element, that would also get this same styling.
ID

An ID is when you'd apply characteristics to one element. To create an ID, you need to use the
attribute id in the HTML opening tag. Then in your CSS, you use the same name you gave the id
attribute in your HTML, except you place a # in front of it.

Example:

//HTML

<h1 id="main-heading"> Welcome to My Page! </h1>

//CSS

#main-heading {

background-color: orange;

If you want to apply a style to more than one element, you should always use a class. You
should only use an ID to style one element. IDs are unique.

Selectors: Combining

Here are some important CSS terms that you've learned so far:

DOM (or Document Object Model) is a tree structure with a node for each HTML element, piece
of text, image, and any other object in the web page.

Selectors are one part of the CSS ruleset. They indicate which HTML element(s) the rule is for.

Example:

h3 {

text-decoration: underline;

h3 is the selector in this example.


Declaration blocks are the other part of the CSS ruleset, they say how the rule will modify the
elements indicated by selectors.

In the above example, the declaration block includes the declaration of text-decoration:
underline;.

CSS rulesets are composed of a selector followed by a declaration block.

Here are some examples of CSS rulesets:

.navigation-links {

font-weight: bold;

color: aqua;

#footer {

width: 100%;

background-color: purple;

li {

font-size: 10px;

margin-bottom: 10px;

type is the simplest kind of selector. It indicates the name of one type of HTML element (such
as em or li).

In the above example, the type selector would be li.

class in HTML is an attribute that groups elements together that you want to have the same style.

In the above example, the class selector would be .navigation-links.

id is an attribute that must be unique to a single element, used to identify it.


In the above example, the ID selector would be #footer.

You've now learned about three kinds of CSS selectors: type, class, and ID!

Type selectors are used to apply a style to a particular type of HTML element, like h1 or body.
Type selectors are written using just the type name.

Class selectors are used to set the style for multiple HTML elements that have a particular value
for the class attribute. You can name a class anything you want! Class selectors are written with
a dot before the class: for elements such as <p class="blue">, the class selector is .blue.

ID selectors are used when the style is being applied to one HTML element, which has to have
an id attribute. There can be only one element with a particular id on a page. You can also
choose any name you want for an id, just like a class. ID selectors are written using a # sign: for
an element such as <div id="sidebar">, the id selector is #sidebar.

Use this HTML document to answer the quiz below.

<html>

<head>

<style>

.special {

color: purple;

p{

font-style: italic;

#important-information {

font-weight: bold;

</style>

</head>
<body>

<h1 class = "special">This header is special</h1>

<p>A nice paragraph in italics.</p>

<h1>This header isn't so special.</h1>

<p>And this paragraph will be in italics too!</p>

<p id = "important-information">This paragraph needs to be italicized and bolded!</p>

</body>

</html>

Question 1 of 8

What does this CSS ruleset do?

li {

color: green;

Applies a style to multiple (but not all) li elements.

Applies a style to all li elements on the page.

Applies a style to a single li element.

Submit

Question 2 of 8
Here's a CSS ruleset:

li {

color: green;

margin:20px;

Can you name each piece?

These are the correct matches.

CSS

What is it?

li

selector

color: green;

declaration / rule

color: green;

margin: 20px;

declaration block

color

property

green

value

Question 3 of 8

We've talked about three kinds of selectors—type, class, and id.


Suppose that you want to use these to style some paragraph p elements. Match each selector type
with what you'd do with it.

These are the correct matches.

To do this ...

... what kind of selector would you use?

To apply the same style to all p elements.

type

To apply the same style to multiple (but not all) p elements.

class

To apply a style to a single p element.

id

Question 4 of 8

Here's some code that uses an ID selector:

<style>

#introduction {

font-weight: bold;

</style>

<p id="introduction">Welcome to my page ...</p>

This code can be divided into two parts. One part defines the style and the other part applies the
style to an HTML element. Which is which?

These are the correct matches.

Code

What does it do?

#introduction {
font-weight: bold;

Defines the style

<p id="introduction">Welcome to my page ...</p>

Applies the style

Question 5 of 8

Here's some code:

<style>

.highlight {

background-color: yellow;

font-weight: bold;

</style>

<h1 class="highlight">I'm important!</h1>

<h2 class="highlight">As am I!</h2>

<p class="highlight">Me too!</p>

What is this code doing?

Using a single class selector to apply the same style to multiple HTML elements.

Question 6 of 8

And here's some of the same code again:

<p class="highlight">I'm important!</p>

What kind of a thing is class="highlight"?


An attribute of this p element.

Question 7 of 8

Here are a few different CSS rulesets. But the syntax is wrong on some of them. Can you spot
the ones with syntax errors?

These are the correct matches.

Selector

Correct or incorrect syntax?

li {

font-size: 1.5em;

color: blue;

Correct syntax

h1 {

font-size: 1.5em

color: blue;

Incorrect syntax

p{

text-align; center:

Incorrect syntax

h2 {

text-align: center;
}

Correct syntax

Question 8 of 8

Sometimes you'll want to apply multiple rules (also called declarations) to the same element.
Like you might want to have all p elements have both color: green and text-align: center.

When you want to put multiple rules in a single ruleset, what do you need to put between each
rule to separate them?

A semicolon ;

Submit

Styling my to-do list

In the workspace below, you'll find my to-do list. But the list is very boring and I'd like to add
some styling to it.

To start with, I'd like to increase the text in the list by making it 1½ times bigger than the current
font size. That can be done using the following declaration:

font-size: 1.5em;

You can apply this style rule to all of the list item li elements by using a type selector. Give it a
try!

If you get stuck, the solution is below.

After starting your workspace, remember to keep the page open. Closing the page will shut down
the workspace and halt any associated processes.

Solution

<style>

li {

font-size:1.5em;

}
</style>

<h1>To-do:</h1>

<ul>

<li>Buy milk

<li>Buy eggs

<li>Buy flour

<li>Make waffles

<li>Do laundry

<li>Learn to code

<li>Build a robot

</ul>

Note: In our solution, we applied the style to all li elements, but we could apply it to the ul type
and (in this example) it would have the same result.

My to-do list needs more work. I'd like to highlight the most important tasks in yellow. And I'd
also like to cross out the tasks that I've already done. It should look something like this:
You can accomplish this by using two class selectors. I called mine highlight and done, but you
could choose other names if you prefer.

The style declarations (rules) that you'll need are background-color: yellow;and text-decoration:
line-through;.

Solution

<style>

li {

font-size: 1.5em;

.highlight {

background-color: yellow;

.done {

text-decoration: line-through;
}

</style>

<h1>To-do:</h1>

<ul>

<li class="done">Buy milk

<li>Buy eggs

<li class="done">Buy flour

<li class="highlight">Make waffles

<li>Do laundry

<li class="highlight">Learn to code

<li class="highlight">Build a robot

</ul>

So now the important items on my to-do list are highlighted, and the completed items are crossed
out. But what if I want to have an item that is marked as both important and completed? Like
this:
In other words, how can we apply two classes to one element?

This turns out to be pretty easy---we simply put in both of the class names, separated by a space.
Like this:

<li class="highlight done">Make waffles</li>

You can give this a try in the workspace below.

The power of separating style!

Let's do one more thing—I'd like the important list items to really stand out, so let's also make
them bold and red.

You can do that by simply adding a couple more declarations to the ruleset for
the highlight class:

.highlight {

background-color: yellow;

font-weight: bold;

color: red;

Give this a try in the workspace above!


Notice that if we were using inline styles, we would have to apply these changes on every line of
code with an li element. Here we only have seven—but you can imagine how tedious this would
get if we had a long list and needed to update the styles on hundreds of list items!

Fortunately, because we have separated the style information, we can make the changes in
only one place (on the highlight ruleset) and they will automatically be applied to all of the
elements that have the highlight class. This is one of the things that makes CSS so powerful!

What's So "Cascading" About CSS?

Cascading and Specificity

The term "cascading" in Cascading Style Sheets refers to the way that style properties "cascade"
down the DOM tree, starting at the top. A style applied to the body element will affect the entire
document. A style applied to a lower-level element will affect that element and all its
descendants.

A style applied at a lower level can override a style at a higher level. For instance, if
the body has color: red but a paragraph within the body has color: blue, the blue will apply to
that paragraph and to any elements inside it:

<style>

body { color: red; }

p { color: blue; }

</style>

<body>

<p> This will be blue, not red. <br>

<em> Same with this. </em> </p>

</body>

Use the HTML below to answer the quizzes on this page!

<html>

<style>
body { font-style: italic; }

h1 { color: purple; }

body { color: green; }

p { color: orange; }

</style>

<body>

<h1> This is a very stylish document! </h1>

<h2> The styles are cascading </h2>

<p> So what color am I? </p>

</body>

</html>

Boxes

Revisiting the div Element

In the video, you may have noticed that Kelly used the div element to create the boxes. We
looked briefly at the div element earlier, but it has been a while—so, let's review the key ideas.

It's used to divide up the page. The name div is short for division, because that's what this
element is for—you can use it to divide up the page into different sections.

It has an "invisible box" around it. Like the paragraph p element, the division div element has an
invisible box around it—and just like p, it can have a border, a margin, a width, a height, and so
on.

It is a generic container. A p element is specifically meant to contain text. In contrast,


the div element is a generic container, meaning you can put whatever other elements you want
inside. You can use the div element to organize the content and divide the page into sections.

The basic syntax is super simple:

<div>

</div>
And, we can texts inside the div, like this:

<div>

Example

</div>

And if we want to apply a style to a div, we can add a class attribute:

<div class="fancybox">

Example

</div>

And then, in our CSS, we can use a class selector with the same name .fancybox to add whatever
styling we want. Here's the example shown in the video:

.fancybox{

border: 5px solid green;

margin: 1em;

padding: 0.5em;

width: 100px;

height: 50px;

float: right;

The div element is used all the time in HTML to structure web pages, so you'll be seeing a lot
more of it as you continue. On this page, we'll just be using the div element to play around with
boxes and adjust the margin, padding, border, etc.

Quiz Question

With so much being invisible and happening behind the scenes, it can often get confusing where
margin, padding, border and content all fit.

To help get it sorted out in your head, see if you can put the parts of a box in order, with 1 being
the innermost part and 4 being the outermost—as shown in this image:
1 (innermost)

Content

Padding

Border

4 (outermost)

Margin
Blue box

In the workspace below, practice making your own boxes! See if you can use the div element to
make a box with a thick blue border and some text inside, like this:

Blue box

Note: The numbers in your code (for margin, padding, and so on) don't need to be exactly the
same—the purpose of the exercise is just to make something that looks approximately like the
box pictured.

<style>

.blue_box {

border: 10px solid blue;

padding: 0.5em;

width: 150px;

height: 100px;

</style>

<div class="blue_box">Hooray, a box!</div>

Let's add a second box. But let's make it small, and red. Let's also put some margin around both
boxes, so that they aren't mashed right up against each other.

Something like this:


<style>

.blue_box {

border: 10px solid blue;

padding: 0.5em;

margin: 0.5em;

width: 150px;

height: 100px;

.red_box {

border: 10px solid red;

padding: 0.5em;

margin: 0.5em;

width: 20px;

height: 20px;

</style>

<div class="blue_box">Hooray, a box!</div>


<div class="red_box"></div>

Your blue_box class should now look like this:

.blue_box {

border: 10px solid blue;

padding: 0.5em;

margin: 0.5em;

width: 150px;

height: 100px;

float: right;

Let's try one more thing—add a paragraph of text at the very end (after both boxes). You can use
this paragraph:

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua. Mi sit amet mauris commodo. Vitae elementum curabitur vitae
nunc sed velit dignissim sodales ut. Volutpat est velit egestas dui id ornare arcu. Nulla facilisi
nullam vehicula ipsum a arcu cursus vitae congue. Porttitor lacus luctus accumsan tortor posuere
ac ut consequat. Et malesuada fames ac turpis. Posuere lorem ipsum dolor sit amet consectetur
adipiscing. Sed risus ultricies tristique nulla. At auctor urna nunc id. Pharetra convallis posuere
morbi leo. Quam quisque id diam vel quam elementum pulvinar etiam. Eleifend donec pretium
vulputate sapien nec sagittis aliquam malesuada. Amet risus nullam eget felis eget nunc
lobortis.</p>

Note: If you're curious what this weird text is all about, it's something called lorem ipsum.
Essentially, it's nonsensical placeholder text that designers commonly use when they're laying
out a document. You can read more about it (and generate your own lorem ipsum) here(opens in
a new tab).

Let's play with the boxes a little more.

If you recall, elements can have contents. Currently, only one of our div elements has contents
—the blue box contains the text Hooray, a box!
But instead of using text for the contents, we could use the other box. To do this, we simply have
to nest the div for the red box inside the div for the blue box (replacing the current
contents Hooray, a box!).

Like this:

<div class="blue_box">

<div class="red_box">

</div>

</div>

Notice how we've lined up the indentation to help make the nesting easier to see.

Give it a try in the workspace!

In case you're not seeing the results described here and need to troubleshoot, here is the complete
code:

<style>

.blue_box {

border: 10px solid blue;

padding: 0.5em;

margin: 0.5em;

width: 150px;

height: 100px;

float: right;

.red_box {

border: 10px solid red;

padding: 0.5em;

margin: 0.5em;
width: 20px;

height: 20px;

float: right;

</style>

<div class="blue_box">

<div class="red_box">

</div>

</div>

Practice: Boxes Inside Boxes

If you recall, elements can have contents. Currently, only one of our div elements has contents—
the blue box contains the text Hooray, a box!

But instead of using text for the contents, we could use the other box. To do this, we simply have
to nest the div for the red box inside the div for the blue box (replacing the current
contents Hooray, a box!).

Like this:

<div class="blue_box">

<div class="red_box">

</div>

</div>

Notice how we've lined up the indentation to help make the nesting easier to see.

In case you're not seeing the results described here and need to troubleshoot, here is the complete
code:
<style>

.blue_box {

border: 10px solid blue;

padding: 0.5em;

margin: 0.5em;

width: 150px;

height: 100px;

float: right;

.red_box {

border: 10px solid red;

padding: 0.5em;

margin: 0.5em;

width: 20px;

height: 20px;

float: right;

</style>

<div class="blue_box">

<div class="red_box">

</div>

</div>

Interpreting percentages
Here is a piece of HTML with CSS. Use it to answer the question below!

<style>

.outer {

width: 300px;

border: 5px dotted orange;

.inner {

border: 5px solid blue;

width: 50%;

</style>

<div class="outer">

<p> This box has a box inside!

<div class="inner">

<p> How wide is the inner box,

<em>including</em> its border?

</div>

</div>

Stylesheet or style element — not both!

Note that you can put your CSS code inside of a <style></style> element, like this ...

<style>

p{color:blue;}

</style>
... or inside of a linked stylesheet, like we just talked about.

But you would not want to do both at the same time! In other words, when you place your CSS
in a stylesheet, you don't need to use a style element—you can just put the CSS directly into the
stylesheet with nothing around it:

p{color:blue;}

This is what you should do for the exercise below—simply put the CSS directly into
your style.css file (and don't use the style element).

Linking stylesheets

To link to a stylesheet in your HTML file, add a link element to the head of the HTML file. The
syntax for the link element is just like this:

<link rel="stylesheet" href="style.css">

If you are linking to a stylesheet located on another web server, you will use a full URL in
the href attribute. If you're linking to one that's in the same directory as your HTML file, you can
just use the filename as a relative URL.

Creating a CSS file

You might think that creating a CSS file requires something special, but all you have to do is
make a new text file (just plain old text!) and rename it with the extension .css. This is similar to
how we create our HTML files—they are simply text files that have a .html file extension in the
name.

Troubleshooting

When you first start using a separate CSS stylesheet, it is very common to have trouble getting
things to work.

If you have made both your .html file and your .css file and the styles just don't seem to be
showing up, you can try copying and pasting our code below into your files.

If our version works, you may have had a typo in yours.

The HTML file

Here's what the code in your HTML file might look like:

<head>

<link rel="stylesheet" href="style.css">


</head>

<p>

Here is an html file that you can use to experiment with your styles.

</p>

The CSS file

And here is what your CSS file might look like:

p {color:purple; font-size:24;}

(Yes, your styles.css file can really contain just that one line and nothing else!)

Linking Trouble

If you still don't see the styles changing, it's probably not linked correctly. There are two
common mistakes that can happen with the link element.

Mismatched Names

The name of the file in the link element must match the way you named your CSS file exactly.
For instance, if you name your file style.css, but then link to styles.css (with an s at the end
of styles), it will not look in the right location to get the style info. The names must match
exactly for the link to work.

Wrong Filepath

If the name is correct and it is still not working, check to make sure the HTML file and the CSS
file are in the same folder. In the gif below, style.css was created in a separate folder, called My
Folder so the styles are not showing up on the page. To fix this, we can either move the file out
of that folder or we can edit the path in the link element to include the folder name, as in My
Folder/style.css.

The code in the HTML file should look like this:

<link rel="stylesheet" href="style.css">

<style>
p {color: blue;}

</style>

<p style="text-align: center;">Style me 3 ways!</p>

And the stylesheet (style.css) should look like this:

p{

font-size: 24pt;

Color

It has to do with how we are mixing the colors. When we mix a material like paint the physics of
how the color will look behaves very differently from when we mix together wavelengths of
light (which is what we need to do when lighting up pixels in a computer screen). If you're super
curious, you can check out this article about primary colors from How Stuff Works(opens in a
new tab).

But for these lessons, all you really need to remember is that computers use RGB colors—that
is, red, green, and blue.

Additional Resources

If you were extremely observant you may have noticed that at the end of the video (above), Kelly
mentions HSL color. We didn't mean to get into that here, but if you're curious, HSL stands for
Hue, Saturation, and Lightness. If you like, you can check out the w3schools.com page on HSL
color(opens in a new tab). If you scroll down on the page, they even have a live example you can
play with to see how HSL colors work.

In school, you may have learned that the primary colors are red, yellow, and blue. But in the
video, Kelly said they are red, green, and blue. What's up with that?

It has to do with how we are mixing the colors. When we mix a material like paint the physics of
how the color will look behaves very differently from when we mix together wavelengths of
light (which is what we need to do when lighting up pixels in a computer screen). If you're super
curious, you can check out this article about primary colors from How Stuff Works(opens in
a new tab).

But for these lessons, all you really need to remember is that computers use RGB colors—that
is, red, green, and blue.

Kelly showed three different ways to represent color values in the code. For example:

rgb(100%, 100%, 100%)

rgb(255, 255, 255)

#ffffff

Although they look different on the surface, they all work essentially the same way.

In all cases, we need to give the amount (or you could say the intensity) of each of the three
primary colors: red, green, and blue (RGB).

Kelly showed three different ways to represent color values in the code. For example:

rgb(100%, 100%, 100%)

rgb(255, 255, 255)

#ffffff

Although they look different on the surface, they all work essentially the same way.

In all cases, we need to give the amount (or you could say the intensity) of each of the three
primary colors: red, green, and blue (RGB).

rgb (100%, 0%, 0%)

Bright red

rgb(0%, 0%, 100%)

Bright blue

rgb(0%, 40%, 0%)

Dark green
rgb(255, 0, 0)

Bright red

rgb(0, 0, 255)

Bright blue

rgb(0, 102, 0)

Dark green

We've been using the words "amount" and "intensity". What we really mean by this is
the brightness of the light. Higher values indicate brighter (more intense) light, and lower values
indicate darker (less intense) light.

By mixing different levels of red, green, and blue, we can get different colors, at different levels
of brightness.

By the way, this way of thinking about light isn't limited to our code—if we were to get real,
physical lights and overlap them, we would get similar results.

Red, green, and blue light overlap to create secondary colors and white light.
(Public domain image from Wikimedia Commons(opens in a new tab))

In the image above, notice that if we mix equal (and intense) levels of all three colors, we get
white light. And you can probably imagine that if we lowered the intensity of all three colors by
equal amounts, we would get various shades of gray.
rgb(100%, 100%, 100%)

white

rgb(30%, 30%, 30%)

dark gray

rgb(0, 0, 0)

black

rgb(255, 255, 255)

white

These look strange, but they work the same way. Each pair of digits is a number that gives the
intensity of red, green, or blue. The reason these values look strange is because they're in a
different number system—instead of the decimal(opens in a new tab) system that we are used
to working with, these numbers are given in the hexadecimal(opens in a new tab) system.

You don't need to have a deep familiarity with hexadecimal to be able to use hex color values on
your pages—but we'll briefly explain the basics so that you can get a feeling for how they work.

Hexadecimal is not as complex as it might appear. Instead of having 10 digits (0, 1, 2, 3, 4, 5, 6,


7, 8, 9), hexadecimal has 16. Since we don't have 16 number symbols, hexadecimal counts up to
9 and then starts using letters.

Here is how we would show the numbers 0-15 in decimal and hexadecimal:

| Decimal | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | |---|---|---|---|---| | Hex | 0 | 1 |


2|3|4|5|6|7|8|9|A|B|C|D|E|F|

Notice that it's the same until we get to 10, which is represented as A in hexadecimal.

Like we mentioned, each pair of digits in a hex RGB value gives the intensity of red, green, or
blue. This ranges from 00, meaning zero intensity, to ff, meaning maximum intensity. In fact, the
number ff is the same as the decimal number 255.

This may seem very alien, but take a try at the following exercise—just to get a feeling for how
hex values work.
#000000

Black

#ffffff

White

#ff0000

Bright red

#0000ff

Bright blue

If you need to find out what the hex value is for a particular color, you can easily find out by
using one of the many color picker tools that are available.

Check out this color picker from W3Schools(opens in a new tab).

You can enter a color in whatever format you like, and it will tell you what other values can be
used to represent that color.

Go to the W3Schools color picker(opens in a new tab) and try entering rgb(0%, 100%,
100%).

What other ways does it say we could represent this color?

#00ffff, aqua or rgb(0, 255, 255)

If you haven't already, we encourage you to play around with the three different kinds of RGB
values we've shown here. Below is a workspace so you can try them out.

We've added a linked stylesheet (the second tab in the workspace) with some CSS type selectors
that are already adding color to the background of the body and h1 elements. But they're using
simple color words (black and white) rather than using RGB values (also, black and white are
the default values, so this isn't really doing anything).

Go ahead and replace the black and white with different RGB values. You may want to use
the W3Schools color picker(opens in a new tab) to find some colors you like.
There are so many CSS properties out there, it's difficult to know (or remember) them all! And
even if you do remember the property you want, you may not be able to recall the exact syntax.
(Was it text-align: center; or text-align: centered;?

Even experienced developers don't have every single property memorized. Fortunately, it's
usually easy to find what you need by looking it up in the documentation or using your favorite
search engine.

Most of the time, you can simply type in "CSS", followed by some words related to the property.
For example, if you want to know how to set the background color, searching for "css
background color" will turn up the results you're looking for.

And as we've mentioned previously, the Mozilla Developer Network(opens in a new tab) is a
good resource to keep in mind (it also has a search option you can check out).

Font vs Typeface

If you have worked in a word processor (like Microsoft Word, for example), you may have seen
things like Times New Roman, Courier, Arial, or Helvetica. For example:

This Text is in Times New Roman

In word processors (and everyday speech) we would call this the "Times New Roman font". But
technically, "Times New Roman" is not a font—it is a typeface.

Wait, what?

Most typefaces have multiple versions that look a little different from one another. For example,
we have:

Times New Roman italic

And also:

Times New Roman bold

These are all examples of the same typeface. but each one is a different version or font.

A typeface is a group of related fonts.


A font is a specific version of a typeface.

Font Families
Another term we can use for a typeface (or group of related fonts) is a font family. That's the
term that CSS uses.

In other words, to change the typeface of our text, we can use the font-family property. Like this:

font-family: Helvetica;

Or here's another example:

font-family: "Times New Roman";

Note: You might notice that one of these has quotes " " while the other does not. The quotes are
recommended for font families that have spaces in the name. They help ensure that the name is
read as one thing ("Times New Roman"), rather than potentially three separate things
(Times, New, and Roman). The spaces don't usually cause a problem, so this is a recommended
practice, not a requirement (you can leave them off and it will typically still work).

Your CSS file should look something like this:

h1{

font-family:Impact;

p{

font-family:Helvetica;

Generic Font Families and Font Stacks

Sometimes we don't care about the specific font family, but we do need the text to use a general
kind of font family. For this, we can use generic font families.

Monospace as an Example

Compare these three examples:


This is an example

This is an example

This is an example

Each of these uses a different font family (or typeface). If you're curious, they
are Courier, Courier New, and Source Code Pro.

Even though they are different font families, they are all examples of monospace font families.
In a monospace font family, every character is the same width—so, for instance, these two letters
are the same width:

Monospace font families are really useful for writing code because they ensure that everything
lines up exactly as expected:

This is 27 characters long! And this is the same length

We would not want to be writing our HTML or CSS and have different bits of our code be
different lengths depending on which letters are in that part of the code!

So if we were putting some code on a web page, we might not care exactly what font family it
uses, but we would want to make sure it is some kind of monospace.

Generic Font Families

That's where generic font families come in. There are five, each named for a general kind of
typeface:

Serif

Sans-serif

Cursive

Fantasy

Monospace

In CSS, we can use a generic font family in place of a specific font family. For example, this line
specifies the specific font family Courier:

font-family: Courier;
In contrast, this one simply says to use whatever monospace font family is available

font-family: monospace;

Font Stacks

Since we don't know what font will be available to each user, it's a good idea to give multiple
options. CSS allows us to do this by using a font stack, like this:

font-family: Courier, "Courier New";

As you can see, we simply list the font families that are OK to use, with the most-preferred
choice first. If that choice isn't available, it will try the next one, and so on.

A common (and very good) practice is to put the generic font family at the end of the list, like
this:

font-family: Courier, "Courier New", monospace;

This way, if none of the other font families are available, the browser will still use the right
general type.

There are many different font families you can use. Here are a few different examples of what
your CSS file might look like. Each one provides a couple of specific font families and then ends
with the relevant generic font family:

Monospace:

p{

font-family: "Courier New", Courier, monospace;

Serif:

p{

font-family: Times, "Times New Roman", serif;

Sans-serif:

p{
font-family: Verdana, Helvetica, sans-serif;

Additional Resources

If you're curious to learn more, you can find additional details and some interactive examples in
the MDN Web Docs on the font-family property(opens in a new tab).

When you need to know what font families to use in a stack, you can check
out cssfontstack.com(opens in a new tab). When you click on a font family, it will tell you
what other fonts you might want to put in the same stack, and it even shows the CSS you would
use for each one.

Font Size

To change the font size, we can use the font-size property, like this:

font-size: 24px;

In this example, px stands for pixels.

Bold

To make the text bold, we can use the font-weight property, as in:

font-weight: bold;

Italic

To make the text italic, we can use the font-style property:

font-style: italic;

Underline

To make the text underlined, we can use the text-decoration property:

text-decoration: underline

Here are all those properties applied to the paragraphs p elements:

p{

font-size:48px;
font-weight:bold;

font-style:italic;

text-decoration:underline;

The Shorthand font Property

It can get a bit tedious typing all the different properties out individually. Fortunately, there is
a shorthand way to do this by using the font property.

For example, instead of typing out:

font-style: italic;

font-size: 24px;

font-family: Times;

We can simply use:

font: italic 24px Times;

…but it has to be in the right order

Like Karl mentioned at the end of the video, the downside to the shorthand is that things need to
be listed in a specific order, and it's kind of easy to forget what that order is. Here are all the
properties you can set using the font shorthand and the order in which you would specify them:

font-style

font-variant

font-weight

font-size

font-family

Or to put that in context:

font: font-style font-variant font-weight font-size font-family;


Here's an example that uses all five properties:

font: italic small-caps bold 24px "Times New Roman";

If you're able to memorize that, great! If not, you can do what Karl does and just look it up when
you need it. You can find it in this CSS-TRICKS article(opens in a new tab), listed near the
top of the CSS font property documentation from W3Schools(opens in a new tab)—or
simply Google "font shorthand order".

Wait, what if I leave something out?

There are two properties that are required when you use the font shorthand: font-size and font-
family. Everything else is optional. If you leave out one of the optional properties, it will just use
the default.

For example, this specifies the font-style:

font: italic 24px Times;

But this one leaves it out:

font: 24px Times;

Since the font-style isn't specified, it defaults to normal (i.e., not italic).

Key Points About the font Shorthand

So, to summarize the three key points you need to remember:

Font size and font family are required

Things need to go in the right order

If you leave an optional property out, it will use the default

p{

font: small-caps bold 24px Courier;

font-weight: bold;

font-style: italic;

font-size: 14pt;
text-decoration: underline;

Or we can combine all of this styling info into one declaration, by using the short-
hand font property. This can be very convenient!

What's not so convenient is that the values for the font property have to be in a certain specific
order or they won't work—and it's easy to forget what that order is! This is a great example of
why it's important to get practice looking things up in the documentation (or even just searching
the web until you manage to dig up the info).

h1 {

font: italic 28pt Impact, "Franklin Gothic Bold", "Arial Black", sans-serif;

p{

font: bold 16pt Consolas, "Courier New", Courier, monospace;

Something you may have wondered is why we have both <strong></strong> and font-weight:
bold;. If you want to bold some text, it seems like you could use either of these—and they would
have the same results.

And the same seems to be true of <em></em> and font-style: italic;.

Why would we need CSS style properties like font-weight and font-style, when we already have
HTML elements like em and strong?

There are a couple of reasons for this.

The historical reason is that HTML was created before CSS, but the engineers who designed
CSS wanted it to provide more customization than HTML alone did. The default way to show
emphasis is by styling it as italic. But we don't have to do it that way — we can use CSS to
override the default styles. For example, we could say that we want emphasized text to be red, or
in a larger font size.

But the differences go deeper than that. HTML code isn't only used by browsers that display on
the screen. It's also used by search engines, smart speaker apps, and other programs. Those
programs can't see "boldface" or "italics", but they still need to know which text on a page
is more important.
The em and strong elements specify the meaning of their contents. In contrast, the CSS style
properties are just specifying the visual appearance.

To repeat this in more general terms: the HTML indicates what the contents mean, while the
CSS indicates how the contents should look. Web programmers refer to this as semantic
markup — using markup to indicate meaning, not just appearance.

For example, if we place some text inside an em element, this is our way of indicating that this
text should be emphasized in some way. But to a program that's reading the page aloud to the
user, it won't use italics; it will use tone of voice. And even in a page that is displayed to the user,
you might want it to be emphasized using color or another property, instead of with italics.

In fact, why don't you give that a try. In the workspace below, you'll find some text that uses a
bunch of em elements. Apply a CSS ruleset to these that makes them red and bold, but not italic!

Hint: You'll need to look up what CSS property and value you can use to remove the italics.

em {

font-weight: bold;

color: red;

font-style: normal;

Notice how there were a ton of em elements, but you only needed to add the style ruleset in one
place to change the appearance of all of that content. This is one of the advantages of separating
the structure and meaning of the content from the style of the content.

Earlier, we saw that we could put boxes inside other boxes. If those boxes are div elements, then
we simply nest the div elements inside one another:

<div>

<div>

</div>

</div>

One reason to nest boxes like this is so that you can use one of the boxes as a container for the
other boxes. To get an idea of why this would be useful, let's take a look at an example.
In the workspace below, you'll find three boxes stacked vertically (notice that they're
currently not inside a container). You'll also see that there's a linked stylesheet, and that we've
styled the boxes using some different classes.

Suppose that we want to get all three of the boxes to stay in a vertical stack, but move over to the
right side. How can we do this?

Well, first let's try this: Add float:right; to the .box class, so that the boxes float on the right side
of the page. Then answer the questions after the workspace.

OK, so trying to float the boxes on the right individually didn't do what we wanted—they ended
up in a horizontal row, rather than staying in a vertical stack.

To solve this, we can put the three boxes inside a fourth box. By wrapping them in a container
like this, we can then move the container around without changing the arrangement of the boxes
inside.

Code for containers.html:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Containers</title>

<link rel="stylesheet" href="containers_style.css">

</head>

<body>

<div class="container">

<div class="box red">red</div>

<div class="box green">green</div>

<div class="box yellow">yellow</div>


</div>

</body>

</html>

Code for containers_style.css:

.container{

float: right;

.box{

width: 100px;

height: 100px;

text-align: center;

font-size: 30px;

font-weight: bold;

font-family: sans-serif;

.red{

background-color: red;

.green{

background-color: green;

}
.yellow{

background-color: yellow;

In the workspace below, you'll find all of the code that Kelly started with in the video. Go ahead
and try applying the two flexbox properties that Kelly demonstrated (display and flex-wrap).

Note that these get added to the container element, not the inner boxes.

In case you're having trouble and need to troubleshoot, here's Kelly's full CSS code:

.container{

width: 100%;

display: flex;

flex-wrap: wrap;

.box{

width: 100px;

height: 100px;

text-align: center;

font-size: 30px;

font-weight: bold;

font-family: sans-serif;

.red{

background-color: red;
}

.green{

background-color: green;

.yellow{

background-color: yellow;

Additional Resources

It's not required for this course, but if you want to understand the concepts and options in more
detail, you may enjoy reading this documentation from Mozilla for the flexible box layout
(aka "flexbox")(opens in a new tab). This is pretty advanced, so don't be surprised if you find
it challenging. If you want to, you can play with the workspace above (or one of your local
HTML files if you're experimenting on your own computer) to see what you can do. For
example, can you use the documentation to figure out how to write flexbox code that results in a
two-column layout?

When using flexbox, it's important to understand how the size of the container element affects
the layout of the boxes that are inside of it.

You may have noticed that in Kelly's code, the width of the .container class is set to 100%. That
means the container will be as wide as whatever it's inside—in this case, the container is inside
the body element of the page, so it will take up the full width of the page.

To see this more easily, we can add a border to the container class.

In the workspace below, add border: 5px solid black to the .container class.

In case you need it, here's the full CSS code with the changes we just made:

.container{

width: 200px;

display: flex;
flex-wrap: wrap;

border: 5px solid black;

.box{

width: 100px;

height: 100px;

text-align: center;

font-size: 30px;

font-weight: bold;

font-family: sans-serif;

.red{

background-color: red;

.green{

background-color: green;

.yellow{

background-color: yellow;

}
Let's get some more practice with flexbox. Your job here is to replicate this checkerboard design:

We've given you a little starter code, but it's up to you to create all the boxes and add the correct
CSS.

This is very similar to the code we just went over on the last page, so if you get stuck you can
always look back at that (or check out our solution code below).

Code for flexbox_practice.html:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Flexbox practice!</title>

<link rel="stylesheet" href="flexbox_practice_style.css">

</head>

<body>

<div class="container">

<div class="box red"></div>

<div class="box black"></div>

<div class="box black"></div>

<div class="box red"></div>


</div>

</body>

</html>

Code for flexbox_practice_style.css:

.container{

width: 200px;

border: 5px solid black;

display: flex;

flex-wrap: wrap;

.box{

width: 100px;

height: 100px;

.red{

background-color: red;

.black{

background-color: black;

Ruleset Syntax
The basic syntax of a CSS ruleset has two parts: a selector, and a group of rules, each of which
consists of a property name and the value of that property.

selector {

property: value;

The selector is written first, and then the rules are written inside { curly brackets }. Each rule's
property and value are separated by a : colon, and the rule always ends with a ; semicolon.

Selectors

The selector indicates which HTML elements the rule will apply to. You've seen a few different
sorts of selector: the element selector, the class selector, the id selector, and
the descendant selector.

A type selector applies to every HTML element of a particular type, such as p or em. This
selector will apply to every p element:

p{

color: blue;

A class selector applies to all elements that share a class attribute. The class selector is written
starting with a . (dot):

.narrow {

width: 20%;

In order for the class selector to apply, there have to be HTML elements on the page that use
that class attribute:

<div class="narrow">

This will get the 20% width.

</div>
An id selector applies to an element with a particular id attribute. The id selector is written
starting with a # sign:

#sidebar {

background-color: lightgray;

width: 20%;

float: left;

Within an HTML page, there should be only one element with that id attribute value.

<div id="sidebar">

This will get the background, width, and float values from the sidebar CSS rule.

</div>

A descendant selector is a compound of two simpler selectors. It applies only to an inner element
that is a descendant (on the DOM tree) of a particular outer element.

li a {

color: pink;

The above selector will apply to a elements (hyperlinks), but only those inside an li element (list
item):

<ul>

<li> <a href="https://www.udacity.com/"> Pink Udacity </a>

</ul>

<p> <a href="https://www.google.com/"> Non-pink Google </a>

Rules

A ruleset can be composed of several rules, each of which applies a particular value to
a property of the selected elements. Properties are things such as the color, position, size, and
shape of the element.
h1 { color: red; font-size: larger; }

This rule applies the value red to the property color, and the value larger to the property font-
size.

Some properties allow values that are more than one word long, such as the font property:

body { font: 12pt bold Consolas, Monaco, monospace; }

Font stacks

The font-family and font properties allow you to specify a font stack, a list of font options
separated by , commas. The browser will use the first font in the stack that is available on the
user's system. Usually the last font in the stack should be a generic font name, such
as serif, sans-serif, or monospace.

Colors

There are several ways to specify a color in CSS. Three common ones are hex codes, rgb triples,
and color names.

.orange {

color: #ff9900;

.pink {

color: rgb(100%, 80%, 80%);

.chartreuse {

color: chartreuse;

Flexbox

To change the browser's layout from the default document-based layout to the flexible box
layout, set display: flex on a container element (one that has other elements inside it).

.outer {
display: flex;

border: 2px dotted orange;

.inner {

width: 100px;

border: 1px solid black;

padding: 10px;

Flexbox can be heavily customized! The above will cause .inner HTML elements to be packed in
a row within the .outer element:

<div class="outer">

<p class="inner"> I am a box. </p>

<p class="inner"> I am another box. </p>

<p class="inner"> Hey, I am a box, too! Boxes <strong>rock</strong>. </p>

<p class="inner"> Let's be boxes together. Yay, flexbox. </p>

</div>

To do this, you'll only need to add CSS rules to the file tictactoe.css. (You don't need to edit the
HTML file at all!)

Here are a few hints:

The ul and the li elements have boxes just like the div elements we've been working with. And
you can think about the ul as a container for the li elements.

Like Karl said in the video, you will probably run into a couple of places where you need to look
up CSS properties you haven't encountered before. For example, you'll need some way of hiding
the bullets in the bulleted list. (Karl had to look that up too when he solved the challenge.)
Google is your friend here!
ul{

width: 300px;

height: 300px;

display: flex;

flex-wrap: wrap;

li {

width: 90px;

height: 90px;

font-size: 80px;

font-family: sans-serif;

background-color: lightblue;

margin: 5px;

list-style: none;

text-align: center;

}
or

ul{

width: 300px;

height: 300px;

li {

width: 90px;

height: 90px;

margin: 5px;

float: left;

list-style: none;

font-size: 80px;

font-family: sans-serif;

text-align: center;

background-color: lightblue;

You might also like