Programing Udacity
Programing Udacity
CSS selectors
Overview: CSS building blocks
Next
In CSS, selectors are used to target the HTML elements on our web pages
that we want to style. There are a wide variety of CSS selectors available,
allowing for fine-grained precision when selecting elements to style. In this
article and its sub-articles we'll run through the different types in great
detail, seeing how they work.
Prerequisites Basic software installed, basic knowledge of working with files, HTML basics
: (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.)
Objective: To learn how CSS selectors work in detail.
What is a selector?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell
the browser which HTML elements should be selected to have the CSS property values inside
the rule applied to them. The element or elements which are selected by the selector are referred
to as the subject of the selector.
In other articles you may have met some different selectors, and learned that there are selectors
that target the document in different ways — for example by selecting an element such as h1, or
a class such as .special.
In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they
need to have support in browsers for them to work. The majority of selectors that you will come
across are defined in the Level 3 Selectors specification and Level 4 Selectors specification,
which are both mature specifications, therefore you will find excellent browser support for these
selectors.
Selector lists
If you have more than one thing which uses the same CSS then the individual selectors can be
combined into a selector list so that the rule is applied to all of the individual selectors. For
example, if I have the same CSS for an h1 and also a class of .special, I could write this as two
separate rules.
CSSCopy to Clipboard
h1 {
color: blue;
}
.special {
color: blue;
}
I could also combine these into a selector list, by adding a comma between them.
CSSCopy to Clipboard
h1, .special {
color: blue;
}
White space is valid before or after the comma. You may also find the selectors more readable if
each is on a new line.
CSSCopy to Clipboard
h1,
.special {
color: blue;
}
In the live example below try combining the two selectors which have identical declarations. The
visual display should be the same after combining them.
When you group selectors in this way, if any selector is syntactically invalid, the whole rule will
be ignored.
In the following example, the invalid class selector rule will be ignored, whereas the h1 would
still be styled.
CSSCopy to Clipboard
h1 {
color: blue;
}
..special {
color: blue;
}
When combined however, neither the h1 nor the class will be styled as the entire rule is deemed
invalid.
CSSCopy to Clipboard
h1, ..special {
color: blue;
}
Types of selectors
There are a few different groupings of selectors, and knowing which type of selector you might
need will help you to find the right tool for the job. In this article's subarticles we will look at the
different groups of selectors in more detail.
CSSCopy to Clipboard
h1 {
}
Class selectors target an element that has a specific value for its class attribute:
CSSCopy to Clipboard
.box {
}
ID selectors target an element that has a specific value for its id attribute:
CSSCopy to Clipboard
#unique {
}
Attribute selectors
This group of selectors gives you different ways to select elements based on the presence of a
certain attribute on an element:
CSSCopy to Clipboard
a[title] {
}
Or even make a selection based on the presence of an attribute with a particular value:
CSSCopy to Clipboard
a[href="https://example.com"]
{
}
This group of selectors includes pseudo-classes, which style certain states of an element.
The :hover pseudo-class for example selects an element only when it is being hovered over by
the mouse pointer:
CSSCopy to Clipboard
a:hover {
}
It also includes pseudo-elements, which select a certain part of an element rather than the
element itself. For example, ::first-line always selects the first line of text inside an element
(a <p> in the below case), acting as if a <span> was wrapped around the first formatted line
and then selected.
CSSCopy to Clipboard
p::first-line {
}
Combinators
The final group of selectors combine other selectors in order to target elements within our
documents. The following, for example, selects paragraphs that are direct children
of <article> elements using the child combinator (>):
CSSCopy to Clipboard
article > p {
}
Summary
In this article we've introduced CSS selectors, which enable you to target particular HTML
elements. Next, we'll take a closer look at type, class, and ID selectors.
Which of these pieces of CSS will apply to span elements inside h2 elements?
The selector h2 span matches any span element inside an h2 element, which is just what
we want here!
What do you think happens if the selector on a rule doesn't match any elements in the
page? For instance, what if we have a rule such as ul { color: blue; } , but we don't
have any ul elements?
The rule will not do anything. It is really common to have the same CSS rules for all pages on a
web site; and if a particular page does not make use of a particular rule, that's OK!
Vocabulary Review
If you like, you can download this review as a PDF by clicking here(opens
in a new tab).
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; .
.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).
class in HTML is an attribute that groups elements together that you want to
have the same style.
Selectors Review
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 .
<html>
<head>
<style>
.special {
color: purple;
}
p {
font-style: italic;
}
#important-information {
font-weight: bold;
}
</style>
</head>
<body>
</body>
</html>
Quiz Question
Match the CSS selectors to the style elements they're used in.
p {
font-style: italic;
}
.special {
color: purple;
}
#important-information {
font-weight: bold;
}
CSS Selector
Style Element
ID selector
Type selector
Class selector
Practice: Selectors
li {
color: green;
}
Applies a style to ALL lie elements on the page
li {
font-size: 1.5em;
color: blue;
}
The first example, with the li selector, uses correct syntax. html h1 { font-size:
1.5em color: blue; }
The second example, with the h1 selector, has a syntax error. It is missing a
semicolon ; before the property name color.
p {
text-align; center:
}
The third example. with the p selector, has a syntax error. The author has
swapped the semicolon and colon. The colon : should appear between text-
align and center, and the semicolon ; should appear at the end.
h2 {
text-align: center;
}
The fourth example, with the h2 selector, uses correct syntax.
We use a semicolon ; to show where each rule ends.
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!
<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.
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!
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>
<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>
Which elements of the HTML document are in green?
body is set to green, but if a specific element is set to a different color that will override it!
Correct! h2 has no overriding color style, so it will be whatever color the body style is set to.
Units
1 inch =96 pixels
37.8pixels= I centimeter
72 pt. = 1 inch
Two of these units can be used in CSS for the height of an element.
One of them can't.
CSS allows you to specify heights (and other distances) using inches or centimeters, but a yard
(36 inches) is a much larger unit than we usually use on the web.
Use Developer Tools to inspect the red rectangle here. How big is it?
many cases, Developer Tools will default to showing you sizes in pixels.
What is the relationship between the CSS unit em and the HTML element <em>?
The CSS unit em is named for the size of the letter "M", and comes from print typography. The
HTML element <em> is short for "emphasis". They're spelled the same, and often
pronounced the same, but they have no other relation between them at all.
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.
<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:
Boundary
Placement
1 (innermost)
Content
2
Padding
3
Border
4 (outermost)
Margin
Exercise: 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:
<style>
.blue_box {
border: 10px solid blue;
padding: 0.5em;
width: 150px;
height: 100px;
}
</style>
Practice: Boxes
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.
.blue_box {
border: 10px solid blue;
padding: 0.5em;
margin: 0.5em;
width: 150px;
height: 100px;
float: right;
}
What happened when you added float: right; to the blue_box class?
Note that the red box may shift up, but its horizontal position does not change.
Now try adding float: right; to the red_box class.
What happens?
Make sure you added float:right; to the red_box class with correct syntax.
Also, if the red box is moving all the way to the right, it might be because your
workspace is too small and it is wrapping things to try to fit them on the
screen. Try collapsing the menu and expanding the workspace, as shown
below:
Hm… that shouldn't happen. Double check that you added float:right; to the red_box class
—and that you didn't make a typo in your code.
Let's try one more thing—add a paragraph of text at the very end (after both
boxes). You can use this paragraph:
ou can think of it as the boxes floating on the right side, and the paragraph
flowing around them.
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.
It should look like this, with the red box inside and to the right:
The float: right; property causes the red box to be placed toward the right side
of whatever container it's inside. Since it is now inside the other div, it gets
floated to the right side of that div.
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>
Percentages
Here's an image to refer to when answering the next question:
Question 1 of 2
<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>
Use the HTML and CSS above to answer this question.
How wide will the inner box be, including its border?
The inner box's content will be 50% the width of the outer box's width, which would be 150px.
But the border adds 10px of width — 5px to the left, and 5px to the right.
150px is the width of the inner box's content, but that doesn't include the border.
A few of you who were extra thorough have sent us comments pointing out
that in addition to font-variant: small-caps(opens in a new tab), you can
also use font-variant-caps: small-caps(opens in a new tab). That works
too!
Separating Style
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:
For example, in the workspace below, you can hover over the plus button and
select New File—and then simply name the file styles.css.
Practice: Three Ways to Style
At this point, we've learned three different ways to apply CSS styles to our
HTML elements. This can get a little confusing, so on this page we'll review all
three approaches. Try to notice what is different in each approach, and what
is the same.
As we saw earlier, we can't put CSS code directly in our HTML, because then
the browser will think it is HTML. Instead, we have to have a way of signaling
that the code should be interpreted.
emember, color: blue; is in CSS, which is a different language from HTML! We can't simply
place a piece of CSS code in the middle of our HTML—the browser will think the code is HTML
and not know how to interpret it (actually, in this case, it will just display color: blue; on the
screen, as if it were text).
This approach is called an inline style because the CSS style is added
directly into a line of HTML (by using the style attribute).
The disadvantage to this approach is that we would have to apply the inline
style over and over again—every time we want a paragraph of text colored in
blue, we would have to add this attribute to the p element. What if we had
1,000 p elements that should all be blue? It would get annoying really fast.
It's not fully separated though. With this approach, the CSS is still in the same
file as the HTML.
This approach fully separates the CSS from the HTML. We can even link multiple HTML files
to the same CSS file if we want to!
OK, now it's your turn! In the workspace below, you'll see that someone tried
to apply some styles to some text, but it's not working. See if you can fix it!
Try using all three of the approaches we just discussed, so that you can see
them side-by-side:
Make the paragraph of text centered using the style attribute to apply
an inline style.
Make the text blue using the style element with a type selector.
Make the text big using a linked CSS file (stylesheet). Note that the stylesheet
has already been created for you, but you'll need to add the style to it, and
add the correct link element to your HTML.
Note: Of course, you would normally not use all three of these approaches at
the same time like this—this is just for practice.
<link rel="stylesheet" href="style.css">
<style>
p {color: blue;}
</style>
Color
n 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.
Which of these sentences accurately describes how to make shades of
gray using RGB colors?
To make gray, use equal amounts of red, green, and blue. But if all three colors are equal to
zero, you'll get black; and if all three are the maximum value (255, FF, or 100%) you'll get white.
Try these color codes out in your browser. Which color matches which description?
Color code
Color description
#fed000
yellow
rgb(80, 5, 120)
dark purple
rgb(90%, 90%, 90%)
light gray
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.
Practice: Color
Kelly showed three different ways to represent color values in the code. For
example:
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).
Match each of these RGB values with the color it would produce.
Bright red
Bright blue
Dark green
Match each of these RGB values with the color it would produce.
These are the correct matches.
RGB value
Notice that these are the same colors given in the last exercise. We can represent intensity on a
scale from 0-100% or on a scale from 0-255—they're just different ways of indicating the same
thing.
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.
Match each of these RGB values with the color it would produce.
These are the correct matches.
RGB value
Notice how we can specify maximum intensity of a color using either 100% or 255.
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.
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.
Match each of these RGB values with the color it would produce.
These are the correct matches.
RGB value
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.
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.
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.
Fonts
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:
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:
And also:
These are all examples of the same typeface. but each one is a different
version or font.
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:
Monospace as an Example
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:
i
m
Monospace font families are really useful for writing code because they
ensure that everything lines up exactly as expected:
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.
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:
A common (and very good) practice is to put the generic font family at the end
of the list, 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
Font Shorthand
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.
font-style: italic;
font-size: 24px;
font-family: Times;
We can simply use:
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:
1. font-style
2. font-variant
3. font-weight
4. font-size
5. font-family
font-weight: bold;
font-style: italic;
font-size: 14pt;
text-decoration: underline;
Below you'll find some pieces of code. Which of them are HTML and which are CSS?
Code
HTML or CSS?
<strong></strong>
HTML
font-weight: bold;
CSS
<em></em>
HTML
font-style: italic;
CSS
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.
Why would we need CSS style properties like font-weight and font-style, when
we already have HTML elements like em and strong?
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!
<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.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Containers</title>
</head>
<body>
</body>
</html>
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.
Flexbox
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.
You should end up with a horizontal row of boxes that wraps when the
browser window is resized.
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;
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.
Currently the width is set to 100%. Try changing it to 200 pixels ( 200px).
What happens?
⚠️Make sure you enter 200px and not just 200 . If you leave off
the px you'll get very different results!
As you can see, flex-wrap:wrap; causes the inner boxes to wrap to the second line when the
container becomes too narrow to fit them all horizontally.
n 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;
}
Practice: Flexbox (2/2)
et'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.
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.
Some properties allow values that are more than one word long, such as
the font property:
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>
I am a box.
I am another box.
Hey, I am a box, too! Boxes rock.
Let's be boxes together. Yay, flexbox.
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!)
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;
}
======================
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;
Intro to JavaScript
JavaScript was Created for the Web
JavaScript was created in 1995 to make it easier to add interactive and
dynamic elements to websites.
If you're familiar with using HTML and CSS to create web pages, JavaScript is
the final piece you'll need to make your websites come to life!
Prerequisites
There are no prerequisites for this course.
History of JavaScript
Where Did JavaScript Come From?
The first version of JavaScript was created in just ten days 1995 by Brendan
Eich(opens in a new tab). Eich was working on Netscape Navigator, one of
the Internet's first web browsers. Eich's goal was to add the capability for
dynamic web pages, which, at that time, were simple pages of HTML and
CSS.
JavaScript Today
You can read more about the current standards for JavaScript in MDN Web
Docs: JavaScript(opens in a new tab)
"Julia"
alert("Hello, Julia! How are you?!");
Writing code in the console is a great way to test out simple bits of code, but
as your code gets larger the browser user interface can be awkward. We
recommend using a text editor like VSCode(opens in a new
tab), Atom(opens in a new tab), or Sublime Text(opens in a new tab) to
write your code and pasting your code in the console when you're ready to run
it.
We'll also provide workspaces for the quizzes and activities in this course.
If you didn't, that's okay. Developer tools aren't always the easiest thing to find
in your browser. So, we've decided to help you out by creating this guide to
developer tools!
Google Chrome
The Chrome DevTools are a set of web authoring and debugging tools built
into Google Chrome. Use the DevTools to iterate, debug and profile your
site. Learn more about Chrome DevTools here(opens in a new tab).
Mozilla Firefox
Firefox Developer Tools allow you to examine, edit, and debug HTML, CSS,
and JavaScript on the desktop and mobile. Also, you can download a version
of Firefox called Firefox Developer Edition(opens in a new tab), which is
tailored for developers, featuring the latest Firefox features and experimental
developer tools. Learn more about Mozilla Firefox DevTools here(opens in
a new tab).
To open Firefox Developer Tools, either right-click on any page element and
select Inspect Element or open the Firefox settings menu in the top-right corner
of your browser window and select Developer. Alternatively, you can use the
shortcuts:
Microsoft Edge
Safari
For any Mac users, Safari includes Web Inspector, a powerful tool that makes
it easy to modify, debug, and optimize a website for peak performance and
compatibility on both platforms. Learn more about Safari Web Inspector
here(opens in a new tab).
Opera
Opera is a fast, lean, and powerful web browser. You can open Developer
tools in Opera using the following keyboard shortcuts:
console.log
The Console Is Your Coding Sandbox
The console is a great place to mess around with your code without any long-
term consequences. The console will tell you if there are any warnings or
errors on the page, display any output, or print it with console.log.
console.log("hiya friend!");
Prints: "hiya friend!"
This can be very helpful in figuring out what is going on when you are
debugging your code.
NOTE: You may see some errors or warnings in the console from the site
you're visiting -- and that's okay! Warnings are very common and will not
affect the code you write in this course.
Troubleshooting
For Chrome users, if you don't see the output, click “Default levels” in the
console and make sure that "Info" is checked. Congratulations! You
performed the log action on the debugging console.
Give It a Try!
Let’s use console.log to do something a little more interesting. Here’s a block of
JavaScript code that loops through the numbers 0 through 9 and prints them
out to the console:
Based on this loop's settings, any code written inside the curly
brackets {...} will be repeated ten times. In this case, console.log prints out the
value of i each time the loop runs. Don't worry if you're not sure about what
the syntax means at this point. Later in this course, you will learn more about
how and when to use loops.
console.log Demo
Browser console has other methods that can be very useful when poking
around. For example, try typing console.table(["orange", "strawberry", "banana"]) in
the console. This method will create a table and display the data in it.
You are welcome to explore the console.dir method on your own. Don't be
afraid to tinker!
JavaScript Demo
So you saw how to use console.log to print a message to the JavaScript
console. Now, let’s see how you can use the console as a sandbox to test a
new line of JavaScript in the browser.
Open the Daring Fireball website(opens in a new tab) in a new tab and in
that tab also open up developer tools. Then paste the following code:
document.getElementsByTagName("h1")[0].style.color =
"#ff0000";
NOTE: If you can't access https://daringfireball.net/(opens in a new tab),
try a different website like https://www.udacity.com/(opens in a new tab).
This demo will work on many different websites.
Project Preview
Build an eCommerce Shopping Cart
By the end of this course, you will understand enough JavaScript to build a
fully functioning eCommerce shopping cart for Kirana's Fruit Stand.
The code to connect your products and functions will also be supplied, so you
only need to focus on the JavaScript code.
Data is Important
It helps us:
Data and data types are the building blocks of any programming language
because they help us organize information and determine how our programs
will run.
In this lesson we will learn how to define and manipulate the primitive data
types of JavaScript.
numbers
strings
booleans
undefined
null
Once you're familiar with these data types, you'll see how you can store data
in variables that you can reuse to manipulate data with your code.
Numbers
Numbers
Defining a number in JavaScript is actually pretty simple. The Number data
type includes any positive or negative integer, as well as decimals. Entering a
number into the console will return it right back to you.
3
Returns: 3
There, you did it.
Arithmetic operations
You can also perform calculations with numbers pretty easily. Basically, type
out an expression the way you would type it in a calculator.
3 + 2.1
Returns: 5.1
Operat
Name Meaning
or
Addition a+b Adds a and b
Subtraction a - b Subtracts b from a
Multiplication a * b Multiplies a and b
Division a/b Divides a by b
Modulo a%b Returns the remainder of a / b
Exponent a ** b Raises a to the power of b
You are probably familiar with the basic operators, but you might not have
seen the % operator yet.
We use the modulo operator to return the remainder of a division operation.
This can be very helpful in a lot of programming tasks.
Question 1 of 4
Question 2 of 4
Question 3 of 4
Enter the expressions (one at a time) into the console and determine what
each expression evaluates to.
These are the correct matches.
Expression
2 + 10 - 19 + 4 - 90 + 1
Solution
-92
Expression
-20 + -19 - (-10) - (-1) + 24
Solution
-4
Expression
(10/5) * 4 - 20
Solution
-12
Expression
4096 % 12
Solution
4
Comparing numbers
What about comparing numbers? Can you do that? Well of course you can!
Just like in mathematics, you can compare two numbers to see if one’s
greater than, less than, or equal to the other.
5 > 10
Returns: false
5 < 10
Returns: true
5 == 10
Returns: false
Comparisons between numbers will either evaluate to true or false. Here are
some more examples, so you can try it out!
Comparison Operators
Operat
Meaning
or
< Less than
> Greater than
<= Less than or Equal to
>= Greater than or Equal to
== Equal to
!= Not Equal to
Question 4 of 4
Enter the expressions (one at a time) into the console and determine what
each expression evaluates to.
These are the correct matches.
Expression
43 > 47
Solution
false
Expression
12 == 17
Solution
false
Expression
3 <= 3
Solution
true
Expression
1 != 0
Solution
true
TIP: The values true and false have significant importance in JavaScript. These values are
called Booleans and are another data type in JavaScript. Later in this lesson, you’ll learn more
about why Booleans are so important in programming.
Comments
// You're about to take your first programming quiz!
Before you move onto the quiz, we want to talk about something you'll see
quite often throughout this course: comments!
You can use comments to help explain your code and make things clearer. In
JavaScript, comments are marked with a double forward-slash //. Anything
written on the same line after the // will not be executed or displayed. To have
the comment span multiple lines, mark the start of your comment with a
forward-slash and star, and then enclose your comment inside a star and
forward-slash / *…* /.
/*
this is
a multi-line
comment
*/
Some of the quizzes in this course might include comments that give you hints
or instructions to complete the quiz. Pay attention to those comments!
You may see comments that are used to clarify and document complex code.
This may improve readability, but it often makes more sense to reduce the
complexity by refactoring and simplifying the code. Simpler code is often
better code.
node first-expression.js
Node.js(opens in a new tab) is an open-source backend JavaScript runtime
environment. That basically means that it will run your JavaScript code in the
terminal and return any output that is generated. We'll be using Node to run
the code in our workspaces for many of the quizzes in this course.
⚠️These workspaces will autosave your code -- but it can take a few
seconds.
If you try to run your code before the autosave occurs, you will see an error
like this:
ReferenceError: Cannot access 'variableName' before initialization
Wait a few seconds and try to run the code again.
Strings
Key Points to Remember About Strings
TIP: It is correct to either use double " or single ' quotes with strings, as long
as you're consistent. The JavaScript Udacity style guide(opens in a new
tab) for labs and projects suggests using single quotes to define string literals
-- but your team or organization might follow a different style guide and prefer
double quotes.
Always follow your team's style guide
String concatenation
Strings are a collection of characters enclosed inside double or single quotes.
You can use strings to represent data like sentences, names, addresses, and
more. Did you know you can even add strings together? In JavaScript, this is
called concatenating. Concatenating two strings together is actually pretty
simple!
Question 1 of 3
If you want to have a space in between two words, you need to explicitly add a space! It will not
be added automatically for you.
Question 2 of 3
What do you think will happen when you type "Hello + 5*10" into the JavaScript
console?
You might have thought that an error would happen. But, remember that
strings can be any collection of characters that are surrounded by quotation
marks. The + 5*10 are just characters inside the quotation marks, so the
interpreter will assume the whole object is a string, and output the result as a
string!
"Hello + 5*10"
output: "Hello + 5*10"
Question 3 of 3
What do you think will happen when you type "Hello" + 5*10 into the console?
You've just discovered some peculiar behavior in JavaScript. It’s called implicit type
coercion and it's a feature of JavaScript. JavaScript multiplies the 5*10 to become 50 and
then changes the number 50 into the string "50", so you're adding together the same data
type. This then gets combined with the string "Hello". You'll learn more about why this
happens later in this lesson.
Variables
Variables Allow Us to Store Data!
With variables, you no longer need to work with one-time-use data.
At the beginning of this course, you declared the value of a string, but you
didn't have a way to access or reuse the string later.
greeting = "Hola";
greeting + " World!";
Returns: Hola World!
greeting + " Mike!";
Returns: Hola Mike!
Here's why: in a small program with just a few variables, it's easy to keep
track of the variables and avoid collisions. But when you are working on a
complex project or with a large team. It is very easy to inadvertently overwrite
an existing variable that is hidden in another part of the
program. let and const avoid this issue because they are only available in the
scope where they are declared. Again, more on scope later. For now,
remember:
Best Practice #1
So which should be your default choice? That's easy. Pick the one that gives
you more control: const. Using const means that your program will throw an
error if there is an attempt to change the value of the variable when the code
runs. If that is an intended outcome, you can go back and revise your code to
declare the variable with let. If you did not intend for the value to change,
congratulations! You've just discovered a bug that you can fix before it causes
any problems.
Best Practice #2
If you aren't sure, use const. You can revise your code later to replace
the const with let if needed.
Try to answer these questions using what you know about let and const. If you
aren't sure, open up the console and run these code snippets to see what
happens.
What is the output of this code?
Question 2 of 5
Question 3 of 5
var still works and will remain working for the foreseeable future! 🤔
You'll see that we use var instead of let and const in some of the demo videos
in this course. While all of the modern browsers support let and const, var is
still part of the language. You'll see it quite often in legacy code.
Naming conventions
When you create a variable, you should write the name of the variable using
camelCase: the first word is lowercase, and all following words begin with a
capital letter. Additionally, aim to use a variable name that accurately yet
succinctly describes what the data represents.
Question 4 of 5
The variables count and postLiked use lowercase and camelCase appropriately.
The postLiked variable has a descriptive name about what it represents.
The count variable is questionable and would depend on its surrounding
context. If the count variable was supposed to track the number of items in a
catalog, then a more descriptive name like catalogCount might be more
appropriate.
As for the other variables, thingy is a vague name that doesn't really describe
what 1 is the value for and firstname should be in camelCase.
Nice work! Even though some of these do not follow best practices for naming, JavaScript is
very lenient about naming. Following naming conventions is important to help
the people looking at the code understand it. The machine that runs it doesn't care.
>F=C×1.8+32>>F=C×1.8+32>
Directions:
Use this equation and the variables fahrenheit and celsius to print the Fahrenheit
equivalent of 12°C.
node convert.js