Work in progress

Learn Selectors

Selectors define the target for the CSS rule you're defining, and up until now, we've only seen one type of selector for elements. The element selector is powerful, because you can modify the display properties of all the instances of that element on a page, but what if you want to be more selective and only target certain elements?

That's where knowing all of the possible selectors comes in handy and can help you:

Class

The class attribute can be applied to any HTML element, and it can be used to span different types of elements, so that you can easily select them in your CSS by using the class selector. The class selector syntax is a period . followed by the class name:

HTML
CSS
Display

David Byrne starts Talking Heads' song Cities with an oxymoronic and humuorous first line, Think of London, a small city.

When applied to a set of song lyrics like this one would appear as:

Think of London, a small city

It's dark, dark in the daytime
The people sleep, sleep in the daytime
If they want to, if they want to

I'm checking them out
I'm checking them out
I got it figured out
I got it figured out
There's good points and bad points
Find a city
Find myself a city to live in...

-Talking Heads

And to this smaller snippet embedded in a sentence as well:

David Byrne starts Talking Heads' song Cities with an oxymoronic and humuorous first line, Think of London, a small city.

The multiple lines of the song above are a blockquote, while the single opening lyric in the previous sentence is a quote element. If we're only using either inline styles or element selectors, then we have a few problems:

However, because we defined a class, then we can simply add the class to each element we want to appear like a lyric, reducing the need to write extra CSS. Now, if we want to style songs the same way on all the pages of our site, we just need to import this stylesheet and then add the lyrics class to the elements representing songs.

The same class can be applied to any number of elements, but what about when you have a truly unique or single element that you want to style in a special or certain way? That's what the HTML id attribute is for.

Identifier

Using the identifier attribute (abbreviated as id in HTML), CSS can target individual elements on a page. As a quick refresher, the value of the id attribute must be unique on a page, meaning one and only one element with that id can exist.

HTML
CSS
edit me
Display

Like the lyrics you just read?

Listen to the Talking Heads Now!

The span element above has both background-color and color properties defined. If you haven't tried it yet, these code examples are editable! You can change the colors and they're update on the page. Try swapping the background-color to blue and the color to gray. You should see something pretty hard to read!

Now that you understand how to use the three different types of selectors, let's learn more about colors.


Back Next: Colors