Skip to main content

Intro to CSS

Learning Objectives - SWBAT:
Style the Elements on a Web Page
Understand the CSS Box Model
Use CSS Selectors to Target Elements for Styling
Include a CSS Framework in a Web Page

Road Map

  1. Setup
  2. Intro to Cascading Style Sheets
  3. The CSS Box Model
  4. The box-sizing CSS Property
  5. CSS Properties
  6. Including a CSS Framework in a Web Page
  7. Adding Styles to a Web Page
  8. CSS Selectors
  9. Summary
  10. Further Study

Videos

Video 📹 Link

1. Setup

This lesson will continue to use the same Repl we used during the Intro to HTML lesson - picking up right where we left off.

2. Intro to Cascading Style Sheets

What is CSS?

CSS is a web technology used to layout and style HTML documents.

The latest version, CSS3, can also provide some stylistic behaviors using CSS animations!

CSS enables us to separate the structure & content (HTML) of a document from its presentation. This concept of separation of concerns is widespread throughout software development because it helps make programs more maintainable and provides better code reuse.

Like most skills related to development, your CSS skills will continually develop over time with each front-end project you're involved with.

Basic CSS Syntax

The following graphic shows the basic syntax of a CSS rule:

h1 {
color: orange;
text-align: center;
}

Let's discuss the individual components above:

  • Selectors:
    • Used to target the element(s) to be styled.
    • Can range from simple to complex.
    • Multiple selectors are separated with commas.
  • Properties:
    • There are over two hundred CSS properties that can be used to style the color, size, text, position, border, animation, etc. of elements.
  • Value:
    • The value to apply to a property is, of course, specific to that property. For example, the CSS property, font-family, accepts values of names of fonts such as Georgia, Helvetica, etc. Other properties may have numeric values along with a type of unit assigned to them, for example, you might set the width of a border to 5px.
  • Declaration:
    • The combination of a property and value, separated by a colon and ending with a semicolon, makes a declaration.

Let's add a CSS rule to add some sizing and a border around the To Do <article> elements:

style.css
article {
height: 4rem;
width: 20rem;
border: 0.5rem solid orange;
}

The rem is a length unit representing the font size of the root (<html>) element. Most browsers default a rem to be equal to 16px.

We will learn more about units as we write code together over time, however, feel free to check out the docs on CSS values and units when time permits.

With the above styling, our page looks something like this:

Time to learn about the CSS Box Model...

3. The CSS Box Model

News Flash: EVERYTHING you see on a web page is a BOX - a rectangle!

When the browser positions and "paints" the elements on the page, it does so according to the following four parts that each element has:

Content Area

The Content Area contains the actual content of the element including its text and other nested elements.

Padding Area

The Padding Area separates the content from the element's border.

The thickness of the padding is set using the padding-top, padding-right, padding-bottom, padding-left, and shorthand padding properties.

Notice how our To Do content is touching the border? We can change that by adding a bit of padding:

style.css
article {
height: 4rem;
width: 20rem;
border: 0.5rem solid orange;
/* Add padding on all four sides */
padding: 0.5rem;
}

Border Area

The Border Area extends outside of the Padding Area. The outer edge of the border is outer most edge of the actual element.

The thickness of the borders are set using the border-width and shorthand border properties.

Margin Area

The Margin Area is used to create an empty area between elements.

The size of the margin area is determined by the margin-top, margin-right, margin-bottom, margin-left, and shorthand margin properties.

Now let's add a bit of space between the <article> elements:

style.css
article {
height: 4rem;
width: 20rem;
border: 0.5rem solid orange;
padding: 0.5rem;
/* Add margin on all four sides */
margin: 1rem;
}

Here's how things look after adding the padding and margin:

4. The box-sizing CSS Property

By default, the box-sizing property is set to a value of content-box and results in the height and width properties sizing the Content Area. Any padding and/or margin will extend beyond the specified height and width!

❓ Based on the default box-sizing described above and since we set a height of 4rem on the article elements, what is the actual height of each article?


6rem

4rem + 2 X 0.5rem (padding) + 2 X 0.5rem (border)


It's preferable to change box-sizing to the more intuitive border-box value so that the element's width and height include everything except the Margin Area.

In fact, most CSS frameworks such as Bootstrap, Materialize, etc., set the default on all elements as follows:

style.css
/* Use the * (general selector) to target all elements */
* {
box-sizing: border-box;
}

With the above change, the <article> elements will now have an actual height of 4rem and a width of 20rem as "expected".

5. CSS Properties

Basic Properties

With over 200 CSS properties in existence, we could spend weeks learning just CSS!

However, let's take a bit of time to research some common properties...

👉 YOU DO: Click on the CSS Properties below to research their purpose and possible values that can be assigned (5 mins)

Shorthand Properties

Shorthand Properties are CSS properties that let you set the values of several individual CSS properties simultaneously.

The font, border and background properties above are examples of Shorthand Properties.

Using a shorthand property, a web developer can write more concise CSS.

A shorthand property groups properties of a common theme. Here are some examples:

font

p {
font-style: italic;
font-weight: bold;
font-size: 12px;
line-height: 14px;
font-family: Helvetica;
}

The five lines of CSS declarations above can be merged into a single declaration as follows:

p {
font: italic bold 12px/14px Helvetica;
}

margin

div {
margin-top: 10px;
margin-right: 5px;
margin-bottom: 15px;
margin-left: 25px;
}

The four lines of CSS declarations above can be merged into a single declaration as follows:

div {
margin: 10px 5px 15px 25px;
}

The above margin example specifies margins for all four sides (top, right, bottom & left - in that order).

A good word to help remember the ordering of these values is TRouBLe (top-right-bottom-left).

6. Including a CSS Framework in a Web Page

There are numerous CSS Frameworks available that can improve the styling of our apps with little effort.

Bootstrap is the most popular CSS Framework in existence.

It's easy to include Bootstrap in a project by simply adding an additional <link> to load its CSS via a Content Delivery Network (CDN):

index.html
<head>
...
<title>Intro to HTML & CSS</title>
<!-- Include Bootstrap -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mqa/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/vI1Bx" crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
</head>
caution

Be sure to add CSS Frameworks BEFORE your project's stylesheet(s) in case you want to override some of the framework's styling.

CSS Frameworks provide lots of predefined classes that can be added to elements.

Let's add Bootstrap's container class to the <body> so that the content no longer touches the edge of the page:

<body class="container">

Adding Bootstrap certainly improved the aesthetics a bit:

7. Adding Styles to a Web Page

There are three ways to add styling to a web page:

  1. Inline Styles
  2. Internal Stylesheets
  3. External Stylesheets

These three techniques are not mutually exclusive, you can use one or more of them in the same webpage.

1. Inline Styles

An inline style can be used to apply style to a single element using the style attribute.

The use of inline styling breaks our separation of concerns by mixing content with presentation and therefore should be avoided unless there's a good reason to do so, for example, when testing or debugging styles.

To demonstrate inline styling, let's use it to change the background color of the page:

index.html
<body
class="container"
style="background-color: SeaShell;"
>

We just used a CSS Named Color instead of using a RGB hex value. There's a link in the References section if you want to learn more about colors in CSS.

2. Internal Stylesheet

The second of the three techniques we can use to add CSS is with internal stylesheets.

An internal stylesheet is created by using a <style> element nested within the document's <head> element.

Let's center the text on the <h1>:

index.html
<head>
...
<style>
h1 {
text-align: center;
}
</style>
</head>

Although an improvement over using inline styling, internal stylesheets are also not the preferred method to add styles to your web page. However, they can be handy for quick styling - like during a lesson 😀

3. External Stylesheets

The last of the three techniques available to add styling is external stylesheets.

Styling a page using external stylesheets is considered a best practice because it provides the best separation of concerns, reusability and maintainability.

External stylesheets are loaded via the <link> element as we've already used to load style.css.

Precedence

When there's a conflict between two or more identical styles with the same specificity (see Further Study)...

The highest priority is given to inline styles using the style attribute.

Then, the loading order determines which style is applied - last one wins because the later style overrides the earlier one. This is what they mean by Cascading Style Sheets.

❓ What's the best practice approach to add styles to a web page?


External Stylesheets loaded using a <link> element


8. CSS Selectors

As shown earlier, the CSS Selector portion of a CSS rule, targets an element, or elements, to be styled.

Basic Selectors

element Selector

This is how we could select all <h1> and <h2> tags:

h1, h2 { ... }

👉 YOU DO: Style by Element (1 min)

  • Target the <span> element and make its text color orange.

Peek only if you must 😀


span {
color: orange;
}

ID Selector

We can select an element by its id attribute by prefixing it with #:

#id-name { ... }

👉 YOU DO: Style an Element by its id (1 min)

  • Target the <section> using its id and add the following CSS declarations:

    margin-top: 1rem;
    border: 0.3rem dotted orange;
    border-radius: 0.5rem;

    Feel free to copy/paste the above

After completion, this is what the page should look like:

class Selector

Selects elements that match one of the values within the class attribute - yes, the class attribute accepts multiple space separated values!

To target elements with a given class, or classes, we prefix the name of the class with a period:

/* Target all elements having the class of "my-class" */
.my-class { ... }

/* Target all <span class="my-class"> elements */
span.my-class { ... }

/* Target all <li class="item special"> elements */
li.item.special { ... }

👉 YOU DO: Style Using a Class (2 mins)

  1. In index.html add a class of todo-input to the <input> element.
  2. In style.css, target any <input> that has a class of todo-input and set a margin-top: 2rem;

Resist if you can 😀


index.html
<input class="todo-input">
style.css
input.todo-input {
margin-top: 2rem;
}

attribute Selector

Selects elements based upon their attributes.

Less common, but handy at times:

/* Matches elements that have a 'style' attribute */
[style] { ... }

/* Targets anchor tags with an 'href' set to "#about" */
a[href="#about"] { ... }

Combinators

Combinators provide a powerful way to select elements based upon their relationship to other elements.

The most common combinator is the descendant selector.

We use the descendant selector to target elements nested within another element, regardless of the depth of the nesting.

A descendant selector is defined by using a space character between two other selectors:

/* This will match all <span> tags nested anywhere within an <h3> tags with a class of "sub-title" */
h3.sub-title span { ... }

The child selector is similar to the descendant selector, except that it only matches elements that are direct children, that is, nested only one-level deep:

/* Selects all <p> tags that are direct children of a <div> */
div > p {...}
info

KEY POINT: The last component listed in a combination selector determines what is actually targeted! For example, looking above, only <p> elements are selected, not the divs with a class of my-class.

Let's update the current <article> selector so that only <article> elements that are direct children of the <section id="todos-container"> are selected:

/* Update this... */
article {
...
}

/* To this... */
#todos-container > article {
...
}

A couple of less common combinators can be found in the Further Study section.

Pseudo-classes

Pseudo-classes let you style elements not just based upon their class, type, id or position in the document, but also their state. For example, whether an
<input type="checkbox"> element
is checked or not.

Pseudo-classes include :hover, :active, :disabled, :empty, :first-child, :nth-child, :nth-of-type, :focus and more!

We can also chain pseudo-classes for some extra big fun!

li:nth-child(3):hover {
...
}

Let's use the :hover pseudo-class to change a To Do <article> element's background color, text color and cursor when the mouse is over it:

article:hover {
background-color: orange;
color: white;
cursor: pointer;
}

Here's a link to learn more about pseudo-classes.

CSS Selectors - Key Takeaways

CSS selectors provide enormous capability and flexibility to target any element(s) for styling!

CSS selectors allow us to target an element, or elements, without having to resort to assigning a bunch of id's.

In general, use classes when you want to apply the styling to multiple elements and use an id to style a single element.

9. Summary

Learning CSS, like much of coding, is a never-ending process and in this lesson, we've done slightly more than scratch the surface.

As you code, you will undoubtedly rely on the numerous resources available to you on the Internet. Hopefully, this lesson has provided you with some context to help you better understand the results returned by your web searches.

Lastly, Chrome's DevTools are invaluable in helping debug among other things, CSS. Here's a link to Google's docs that discuss inspecting and changing CSS

10. Further Study

Specificity

Specificity is the means by which a browser decides which CSS rule gets applied when there is a conflict. For example:

.my-class {
color: blue;
}

div {
color: red;
}
<div class="my-class">What color am I?</div>

A conflict exists because the <div> matches both CSS selector rules.

The selector with the highest Specificity wins.

The specificity is based upon the following priorities, where Priority A has higher specificity:

Priority APriority BPriority CPriority D
Inline StylingIDsClasses, Attributes & Pseudo-classesElements

Internally, the browser computes a CSS Specificity as shown here:

There is an exception to the concept of specificity known as the !important declaration. Use of !important is not recommended because it can make debugging CSS more difficult than it already is.

Margin Collapsing

The top and bottom margins are sometimes combined into a single margin - this behavior is known as margin collapsing.

Less Common Combinators

These combinators are not quite as common but can come in handy...

  • The adjacent sibling selector (+)
div + p {...}

Would select <p> tags only if they were preceded immediately by a <div> at the same level (sibling).

  • The general sibling selector (~)

Similar to the adjacent sibling selector, except that it targets all siblings, not just the adjacent one:

div.my-class ~ p {...}

Would target all <p> tags that are siblings following a <div> with a class of "my-class".

Pseudo-elements

Pseudo-elements style specified parts of an element.

Here are some examples:

  • p::first-letter: Style the first letter of all <p> elements
  • p::first-line: Style the first line of all <p> elements
  • ::selection: Style the part of an element that is selected by the user
  • .special::before: Add content before all elements with a class of .special
  • .special::after: Add content after all elements with a class of .special

Here's a link to learn more about pseudo-elements.

Resources

CSS Reference

CSS3 cheat sheet

CSS Colors

css-tricks

codrops