Cascading Style Sheets (CSS)
CSS, or Cascading Style Sheets, is a stylesheet language used to describe the presentation of a document written in a markup language like HTML. It’s one of the cornerstone technologies of the web, alongside HTML and JavaScript.
CSS allows web developers to control the layout, colors, fonts, and overall visual appearance of web pages, making it possible to create engaging and aesthetically pleasing user experiences. By separating the presentation from the content, CSS makes websites easier to maintain and adapt to different devices and screen sizes.
CSS Selectors
Selectors are used to target the elements you want to style. There are many different types of selectors, but we will start with the most basic: the type selector.
Type Selector
A type selector (or element selector) will select all elements of the given element type, and the syntax is just the name of the element:
<div>Hello, World!</div>
<div>Hello again!</div>
<p>Hi...</p>
<div>Okay, bye.</div>
div {
color: white;
}
Here, all three <div>
elements would be selected, while the <p>
element would not be.
We also begin to see the syntax of a CSS rule:
selector {
property: value;
}
The selector is the element you want to style, the property is the aspect of the element you want to change, and the value is the new value for the property. We will cover more about properties and values in a later section.
Example
What would you expect to happen to an element that has a color
property set to white
? Let’s find out!
Below, we use “inline CSS” to select all <div>
elements and set their color
property to white
. In CSS, color
is a property that sets the color of the text in an element. We also set the background-color
property to black
to change the background color of the element so that the text is visible.
“Inline CSS” is a way to style an element directly in the HTML file using the style
attribute. It’s generally not recommended to use inline CSS, but it’s a good way to demonstrate CSS quickly without having to write a separate CSS file.
Knowledge Check
Which of the following best describes the CSS code given above?
- Select an answer to view feedback.
Class Selector
Class selectors will select all elements with the given class, which is just an attribute you place on an HTML element. Here is how you add a class to an HTML tag and select it in CSS:
<div class="alert-text">
Please agree to our terms of service.
</div>
.alert-text {
color: red;
}
Note the syntax for class selectors: a period immediately followed by the case-sensitive value of the class attribute. Classes are not required to be unique, so you can use the same class on as many elements as you want.
Another thing you can do with the class attribute is to add multiple classes to a single element as a space-separated list, such as class="alert-text severe-alert"
. Since whitespace is used to separate class names like this, you should never use spaces for multi-worded names and should use a hyphen instead.
ID Selectors
ID selectors are similar to class selectors. They select an element with the given id
, which is another attribute you can place on an HTML element:
<div id="title">My Awesome 90's Page</div>
#title {
background-color: red;
}
Instead of a period, you use a hashtag immediately followed by the case-sensitive value of the id
attribute.
A common pitfall is people overusing the id
attribute when they don’t necessarily need to, and when classes will suffice. While there are cases where using an id
makes sense or is needed, such as taking advantage of specificity (which we will cover later) or having links redirect to a section on the current page, you should use IDs sparingly (if at all).
The major difference between classes and IDs is that an element can only have one id
. An id
cannot be repeated on a single page, and the id
attribute should not contain any whitespace at all.
Knowledge Check
What is the syntax for class and ID selectors?
- Select an answer to view feedback.
Combining Selectors
What if you have two groups of elements that share some of their style declarations?
.read {
color: white;
background-color: black;
/* several unique declarations */
}
.unread {
color: white;
background-color: black;
/* several unique declarations */
}
Both our .read
and .unread
selectors share the color: white;
and background-color: black;
declarations, but otherwise have several of their own unique declarations. To cut down on the repetition, you can group these two selectors together as a comma-separated list:
.read,
.unread {
color: white;
background-color: black;
}
.read {
/* several unique declarations */
}
.unread {
/* several unique declarations */
}
Both of the examples above (with and without grouping) will have the same result, but the second example reduces the repetition of declarations and makes it easier to edit either the color or background-color for both classes at once.
Another way to use selectors is to chain them as a list without any separation. Let’s say you had the following HTML:
<div>
<div class="subsection header">Latest Posts</div>
<p class="subsection preview">This is where a preview for a post might go.</p>
</div>
You have two elements with the subsection class that have some sort of unique styles, but what if you only want to apply a separate rule to the element that also has header as a second class? Well, you could chain both the class selectors together in your CSS like so:
.subsection.header {
color: red;
}
What .subsection.header
does is it selects any element that has both the subsection
and header
classes. Notice how there is not any space between the .subsection
and .header
class selectors. This syntax basically works for chaining any combination of selectors, except for chaining more than one type selector.
This can also be used to chain a class and an ID, as shown below:
<div>
<div class="subsection header">Latest Posts</div>
<p class="subsection" id="preview">This is where a preview for a post might go.</p>
</div>
You can take the two elements above and combine them with the following:
.subsection.header {
color: red;
}
.subsection#preview {
color: blue;
}
In general, you can’t chain more than one type selector since an element can’t be two different types at once. For example, chaining two type selectors like div
and p
would give us the selector divp
, which would not work since the selector would try to find a literal <divp>
element, which does not exist.
Combinators
Combinators allow us to combine multiple selectors differently than either grouping or chaining them, as they show a relationship between the selectors. There are four types of combinators in total, but for right now we are going to only show you the descendant combinator, which is represented in CSS by a single space between selectors.
A descendant combinator will only cause elements that match the last selector to be selected if they also have an ancestor (parent, grandparent, etc) that matches the previous selector.
So something like .ancestor .child
would select an element with the class child
if it has an ancestor with the class ancestor
. Another way to think of it is child
will only be selected if it is nested inside of ancestor
, no matter how deep. Take a quick look at the example below and see if you can tell which elements would be selected based on the CSS rule provided:
<div class="ancestor"> <!-- A -->
<div class="contents"> <!-- B -->
<div class="contents"> <!-- C -->
</div>
</div>
</div>
<div class="contents"></div> <!-- D -->
.ancestor .contents {
/* some declarations */
}
In the above example, the first two elements with the contents
class (B and C) would be selected, but that last element (D) will not be. Was your guess correct?
There is really no limit to how many combinators you can add to a rule, so .one .two .three .four
would be totally valid. This would just select an element that has a class of four
if it has an ancestor with a class of three
, and if that ancestor has its own ancestor with a class of two
, and so on. You generally want to avoid trying to select elements that need this level of nesting, though, as it can get pretty confusing and long, and it can cause issues later on.
Knowledge Check
What does the descendant combinator do?
- Select an answer to view feedback.
Adding CSS to your HTML
Okay, you went over quite a bit so far. The only thing left for now is to go over how to add all this CSS to your HTML. There are three methods to do so, one of which you have already seen.
External CSS
External CSS is the most common method you will come across, and it involves creating a separate file for the CSS and linking it inside of an HTML’s opening and closing <head>
tags with a <link>
element (which is a void element and doesn’t require a closing tag):
<head>
<link rel="stylesheet" href="styles.css">
</head>
First, you add a void element <link>
tag inside of the opening and closing <head>
tags of the HTML file. The href
attribute is the location of the CSS file, either an absolute URL or, what you will be utilizing, a URL relative to the location of the HTML file. In the example above, you are assuming both files are located in the same directory. The rel
attribute is required, and it specifies the relationship between the HTML file and the linked file.
div {
color: white;
}
p {
background-color: black;
}
Then inside of the newly created styles.css
file, you have the selector (the div
and p
), followed by a pair of opening and closing curly braces, which create a “declaration block”. Finally, you place any declarations inside of the declaration block. color: white;
is one declaration, with color
being the property and white
being the value, and background-color: black;
is another declaration.
A note on file names: styles.css
is just what you went with as the file name here. You can name the file whatever you want as long as the file type is .css
, though “style” or “styles” is most commonly used.
A couple of the pros to this method are:
- It keeps your HTML and CSS separated, which results in the HTML file being smaller and making things look cleaner.
- You only need to edit the CSS in one place, which is especially handy for websites with many pages that all share similar styles.
Knowledge Check
Which of the following best describes the purpose of the rel attribute in the <link> element when linking an external CSS file to an HTML file?
- Select an answer to view feedback.
Internal CSS
Internal CSS (or embedded CSS) involves adding the CSS within the HTML file itself instead of creating a completely separate file. With the internal method, you place all the rules inside of a pair of opening and closing <style>
tags, which are then placed inside of the opening and closing <head>
tags of your HTML file. Since the styles are being placed directly inside of the <head>
tags, you no longer need a <link>
element that the external method requires.
Besides these differences, the syntax is exactly the same as the external method (selector, curly braces, declarations):
<head>
<style>
div {
color: white;
background-color: black;
}
p {
color: red;
}
</style>
</head>
<body>...</body>
This method can be useful for adding unique styles to a single page of a website, but it does not keep things separate like the external method, and depending on how many rules and declarations there are it can cause the HTML file to get pretty big.
Knowledge Check
Which of the following is a difference between internal and external CSS methods?
- Select an answer to view feedback.
Inline CSS
Inline CSS makes it possible to add styles directly to HTML elements, though this method is not as recommended:
<body>
<div style="color: white; background-color: black;">...</div>
</body>
The first thing to note is that there aren’t any selectors here, since the styles are being added directly to the opening <div>
tag itself. Next, you have the style
attribute, with its value within the pair of quotation marks being the declarations.
If you need to add a unique style for a single element, this method can work just fine. Generally, though, this is not exactly a recommended way for adding CSS to HTML for a few reasons:
- It can quickly become pretty messy once you start adding a lot of declarations to a single element, causing your HTML file to become unnecessarily bloated.
- If you want many elements to have the same style, you would have to copy + paste the same style to each individual element, causing lots of unnecessary repetition and more bloat.
- Any inline CSS will override the other two methods, which can cause unexpected results. (While you won’t dive into it here, this can actually be taken advantage of in more advanced cases).
Knowledge Check
Which of the following is the main disadvantage of using inline CSS?
- Select an answer to view feedback.
A Look Ahead: Working with CSS
In the next lesson, we will give you several exercises to practice what you have learned so far. While everything here may seem overwhelming, once you begin to work with CSS you will start to get the hang of it.