Icon for parent category 'Websites'

The Basic Selectors

Before we can style anything, we first need to select the thing we want to style. This chapter explains a handful of basic selectors—the simplest ones that you’ll use the most often—so we can quickly start with actually creating designs.

Tag Selector

This selects all elements of a certain type. Simply type the tag name. (For example, a <div> element is selected with just div.)

ID selector

When you learned HTML, you hopefully also learned that every element can take an id attribute. This contains a unique identifier (not used by any other element) for this element.

Target such an element with the syntax #id.

Class selector

Similarly, you can assign any number of classes to an element using the class attribute. These don’t need to be unique.

To style all elements of the same class, use .class.

Multiple Selectors

Sometimes, you have a set of styles that you want to apply to several different elements. Fortunately, you don’t have to copy-paste it ten times.

Chain multiple selectors into one by separating them with a comma (,).

Nesting Selector

Finally, you can build a selector with nested parts.

Why? For example, a typical website has paragraphs in many different locations. You probably want a paragraph in your main text (say your blog article) to look different from a paragraph that’s just a remark in your sidebar.

You could assign classes or IDs to all of the different paragraphs. But an easier way is to use something you already have: the hierarchy of your page!

One paragraph will be the child of an <article> element (the blog article). The other paragraph will be a child of an <aside> element (the sidebar).

To create such a selector, add the parts separated by a space ( ). It should read parent to child from left to right. (So later elements are nested inside earlier ones.)

Conclusion

There are more selectors, but they are (very) advanced and will be explained near the end.

I already doubted whether I should include the “nesting selector”, but I choose to do so. Why? Because, next chapter, you will learn how crucial (good) nesting and hierarchy are to CSS as a whole.

Continue with this course
Support me and this website!

Want to support me?

Buy one of my projects. You get something nice, I get something nice.

Donate through a popular platform using the link below.

Simply giving feedback or spreading the word is also worth a lot.