Basic CSS: CSS Selectors

Lesson 3: CSS Selectors

/en/basic-css/adding-css-to-a-webpage/content/

Selectors

If you want to write effective CSS, you first have to be able to choose which specific parts of your HTML you want to style. For example, you might want to style paragraphs, but not lists, or you might want to style just one specific paragraph, but not any others. CSS allows you to make these distinctions using selectors.

Selecting part of a webpage

What is a selector?

The selector is the opening portion of a CSS ruleset that defines what HTML elements the declarations inside the curly braces should affect:

a CSS selector

However, the names of HTML elements—like p above, for example—aren't the only thing that can be used to specify which HTML to target. Two common selectors for CSS rulesets are actually not HTML elements at all, but HTML attributes: id and class.

What is an id?

An id (pronounced "I-D") is an HTML attribute that can be added to any HTML element to act as a unique identifier. Like most HTML attributes, it consists of two pieces:

  • name: the name is always id.
  • value: the value can be anything you want, as long as it doesn't have any spaces in it.

It doesn't matter what particular value you choose, because the id attribute doesn't do anything in and of itself. Think of it like a target you're painting onto an HTML element. When writing CSS or JavaScript for a webpage, any target you add will give you something to aim for.

For example, imagine you've written a few paragraphs in HTML:

<p>Here's my first paragraph</p>
<p>This one's special</p>
<p>Here's my third paragraph</p>

Let's say you want to make the middle paragraph have red text. Now that you're working in CSS, though, you realize that you have to no way to target only that paragraph. You could use a ruleset like this:

p {
  color: red;
}

But that would affect all three paragraphs, and only the middle one should be red. One solution is to add an id attribute to your HTML. The value can be whatever you want, so maybe you'd add this:

id="myFirstId"

And end up with this HTML:

<p>Here's my first paragraph</p>
<p id="myFirstId">This one's special</p>
<p>Here's my third paragraph</p>

If you loaded that HTML in your browser, it wouldn't look any different yet, because the id doesn't do anything on its own. To make the text of that middle paragraph red, you need to select it using that id.

How do you select by id?

You can select an HTML element by its id by using the value you gave the id in the selector of a CSS ruleset. To let the browser know that you're looking for an id, you would format your selector using the number sign (#) symbol, then the value of the id:

#myFirstId

If you wanted to turn the text of that middle paragraph red, then, you could now use a ruleset like this to target just the one:

#myFirstId {
  color: red;
}

Keep in mind that an id is a unique identifier, which means two things:

  • The same id shouldn't be attached to more than one HTML element
  • A single HTML element shouldn't have more than one id.

As with many aspects of web development, the browser works hard to guess at what's intended even when something things are done incorrectly. It may appear at first glance, then, that having multiple identical ids on a page is fine. However, as with most broken rules, any time the browser starts guessing, strange things may eventually start happening.

What is a class?

Like an id, a class is an HTML attribute that can be added to any HTML element to act as an identifier. However, unlike an id, a class does not have to be unique, so the same class can be attached to multiple HTML elements. A class consists of two pieces:

  • name: the name is always class.
  • value: the value can be anything you want, as long as it doesn't have any spaces in it.

Just like with an id, the value of a class doesn't need to be any particular thing, because it doesn't do anything by itself. Instead, it provides a target for selecting multiple elements at once using CSS or JavaScript.

For example, imagine you've written a few new paragraphs in HTML:

<p>Here is a special paragraph</p>
<p>This one's not</p>
<p>Here is another special paragraph</p>

This time, let's say you want to make the first and third paragraphs—the special ones—red, but not the middle one. You could give the first and third paragraphs each their own unique id, then make CSS rulesets for each id that set the text to red. That would be a lot of work, though, and an easier way would be to add a class:

class="myFirstClass"

And end up with this HTML:

<p class="myFirstClass">Here is a special paragraph</p>
<p>This one's not</p>
<p class="myFirstClass">Here is another special paragraph</p>

As with the id, if you loaded that HTML in your browser, it would look unchanged, because the class doesn't do anything on its own. To make the text of the outer paragraphs red, you need to select them using their class.

How do you select by class?

You can select an HTML element by its class by using the class value in the selector of a CSS ruleset. To let the browser know that you're looking for a class, you would format your selector using the period (.) symbol, then the value of the class, like this:

.myFirstClass

If you wanted to turn the text of those outer paragraphs red, then, you could now use a ruleset like this to target both of the outer paragraphs:

.myFirstClass {
  color: red;
}

Even though it's only one ruleset, it would target every HTML element that has the class="myFirstClass" attribute.

Should you use classes or ids?

Given that both ids and classes can be used to specify which HTML elements you want to target, you might find that it's not always clear which you should use. When in doubt, it's usually safest to use classes with CSS since they can be used to style any element (or multiple elements). However, when using JavaScript you'll often need to use both ids and classes for various purposes.

Multiple selectors

You may find that you sometimes you may want to add the same declarations to more than one selector. For example, imagine you want all of the <p> elements on your page to have red text, but you also want that for all of the <button> elements. 

One solution would be to add a separate ruleset for each in your stylesheet, one with p as the selector and another with button as the selector. There isn't anything wrong with that, but if you did it regularly, you'd end up cluttering your stylesheet with repeated declarations. A better solution is to use just one ruleset with multiple selectors. All you have to do is separate each selector with a comma:

p, button {
  color: red;
}

You can do the same thing with ids and classes, too. Just remember that they still require their starting # and . symbols:

#myFirstId, .myFirstClass {
  color: red;
}

Do it yourself!

Open the index.html file in your GCF Programming Tutorials project in your text editor, and let's add some ids and classes. For the best understanding, be sure to actually type this code in, rather than copying and pasting it. 

  1. First, find the <h1> heading that includes your webpage title: 
    <h1>Cinema Classics Movie Reviews</h1>
  2. There is only going to be one main heading for this webpage, so it makes sense to give this an id, given that it's unique. Our id can be whatever we want (as long as it has no spaces), so let's make it simple: 
    <h1 id="header">Cinema Classics Movie Reviews</h1>
  3. Next, find the opening <div> that you wrapped around the majority of your movie review content. 
  4. Eventually, you're going to want to have more than one review. However, you're still going to want them to all have the same sorts of styles applied to them. That's a perfect opportunity to use a class
    <div class="review">
  5. Now open the styles.css file in your GCF Programming Tutorials project.
  6. Find the p ruleset you already added: 
    p {
      color: red;
    }
  7. In your browser, notice that the bullet-point text isn't affected by it, because that text is in <li> elements, not <p> elements. Let's add a second selector to that ruleset so that both will be styled: 
    p, li {
      color: red;
    }
  8. Also, we don't really want red text. Another option to make it more readable, though, would be to make the text a little bit bigger. We'll talk about this more later, but for now, let's just replace that color declaration with a font-size declaration: 
    p, li {
      font-size: 18px;
    }
  9. Next, let's add a new ruleset here that targets your webpage's main heading. You already added an id to it, so let's use that as the selector:
    #header {
    }
  10. Finally, let's add a simple CSS declaration, just to make sure everything's working. We'll also revisit the declaration later on, but for now, add this inside your #header ruleset: 
    #header { 
      text-align: center;
    }

Your full index.html file should now look like this:

<!DOCTYPE html>
<html>
  <head>
    <title>Cinema Classics Movie Reviews</title>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1 id="header">Cinema Classics Movie Reviews</h1>
    <div class="review">
      <h2>Review: Basketball Dog (2018)</h2>
      <img src="https://media.gcflearnfree.org/global/coding/basketballdog.png">
      <p><i>4 out of 5 stars</i></p>
      <p>From director <b>Vicki Fleming</b> comes the heartwarming tale of a boy named Pete (Trent Dugson) and his dog Rover (voiced by Brinson Lumblebrunt). You may think a boy and his dog learning the true value of friendship sounds familiar, but a big twist sets this flick apart: Rover plays basketball, and he's doggone good at it.</p>
      <p>This movie has everything you could ask for:</p>
      <ul>
        <li>Basketball</li>
        <li>A dog</li>
        <li>Nail-biting suspense</li>
      </ul>
      <p>While it may not have been necessary to include all 150 minutes of Rover's championship game in real time, Basketball Dog will keep your interest for the entirety of its 4-hour runtime, and the end will have any dog lover in tears. If you love basketball or sports pets, this is the movie for you.</p>;
      <p>Find the full cast listing at the <a href="https://edu.gcfglobal.org">Basketball Dog</a> website.</p>
      <button>Show Next Review</button>
    </div>
  </body>
</html>

And your full styles.css file should look like this:

p, li {
    font-size: 18px;
}
#header {
    text-align: center;
}

If you load your index.html file in your browser or refresh the page, you should now see your main header centered. It should look something like this.

Congratulations, you've added new selectors!

/en/basic-css/text-styling-in-css/content/