CSS Selectors

Chapter 5 10 mins

Learning outcomes:

  1. What are CSS selectors
  2. Tag, id and class selectors
  3. A combination of these selectors

What are selectors?

Before we can style elements on an HTML page we have to first select them. Whether it's to style all the paragraphs on a page or just a single, tiny anchor element, we have to do selection.

And to select elements in CSS we have what we call CSS selectors.

Selectors are statements used to fetch a given set of HTML elements

The elements selected, all meet a given criteria established by the selector statement. There are various types of selectors in CSS of which some will be discovered in this very chapter and some in the next one.

But before beginning on exploring these different kinds of selectors we will give you some time to think on your own about what things do we know about HTML elements which can help us in selecting them? As an example we know their tag names.

So were you able to think of the answer? Well we know literally a lot about elements in HTML of which tag names like p, a are just one of the list. The rest are their:

  1. Ids
  2. Classes
  3. Attributes - names and values
  4. Parent-child relationships
  5. States

And with so much knowledge about HTML elements it isn't surprising at all that we have a lot to CSS selectors! In this chapter we will explore the first three of the list, leaving the other two for the next chapter.

Tag selector

We'll start with the simplest and easiest of the list of CSS selectors i.e tag selector. You've been working with it for quite a long while uptil now and likewise should be fairly comfortable with using it.

Following is a simple illustration:

<p>A paragraph</p>
<p>Another paragraph</p>
p {color: blue}

A paragraph

Another paragraph

This code simply selects all the <p> elements on the web page and colors them blue.

In a similar way we can select literally all HTML elements based on their tag names like h1 for <h1>, body for <body>, audio for <audio> and so on.

Write CSS to color all HTML anchors (<a>) blueviolet and all span (<span>) elements gold.

To select all anchors we use the selector a whereas for all span elements we use the selector span. After this the styling is just the matter of seconds using the color property and the given color values.

a {color: blueviolet}
span {color gold}

Id selector

HTML elements can have unique ids on a webpage given using the id attribute. Fortunately we can use these ids to select them in CSS.

The id selector, denoted by a hash symbol #, simply selects an element with the given id. The id value follows the hash symbol (without any spaces). Following is the general form of an id selector:

#id {}

Consider the HTML below containing a p element with id p1. We will be using this to select it and color it blue.

<p id="p1">A paragraph with id #p1</p>
<p>Another paragraph</p>
#p1 {color: blue}

A paragraph with id #p1

Another paragraph

Remember one thing that id selectors are meant to select one single element on an HTML page, unlike tag selectors which can also select multiple elements. Ids are unique and so must be HTML elements with ids!

Consider the HTML below:

<p id="p1">A sandybrown background</p>
<p id="p2">A seagreen color</p>
<p id="p3">A sandybrown background and 20px font-size</p>

Write CSS to style this HTML such that it looks as follows.

A sandybrown background

A seagreen color

A sandybrown background and 20px font-size

(The desired styles are written as the content of the elements above.)

We'll select and style all the three elements individually using their respective ids; #p1, #p2 and #p3.

#p1 {background-color: sandybrown}
#p2 {color: seagreen}
#p3 {background-color: sandybrown;font-size: 20px}

Class selector

Multiple elements on an HTML page can share the same class, given by the class attribute. CSS can then select these groups of elements using a class selector.

The class selector, denoted by a period ., selects all elements with the given classname. The classname is followed by the period symbol (once again without any spaces). Following is the general form:

.classname {}

Let's use this idea to select all span elements with the class highlight in the example shown below. The class serves to give yellow backgrounds to its elements i.e it highlights them.

<p>
    I am <span class="highlight">highlighted</span>.
    I am not highlighted.
    I am <span class="highlight">highlighted</span>.
    I am <span class="highlight">highlighted</span> too.
</p>
.highlight {background-color: yellow}

I am highlighted. I am not highlighted. I am highlighted. I am highlighted too.

You are working with a team of developers and designers making the next award-winning web design. The group of developers coding the markup has set up the HTML with different classes. Three of them are given below together with the purpose they serve.

  1. .disabled: gives a grey color
  2. .large: gives a 30px font-size
  3. .stroked: gives a 1px solid black stroke.

Can you write some CSS to put these classes into real styling action?

The question is pretty straightforward - just use the aforementioned classes and declare the desired rules for each of them.

.disabled {color: grey}
.large {font-size: 30px}
.stroked {border: 1px solid black}

Attribute selector

The attribute selector selects all elements with a given attribute name or attribute value.

The attribute selector begins and ends with [] square brackets. Inside them we mention the attribute just like we mention it in HTML.

/* Select all elements with a data-src attribute */
[data-src]

/* Following we select all elements with a title attribute equal to "Hello". */
[title="Hello"]

Notice over here, in the first example, how by omiting =value we can just check for the presence of an attribute.

Universal selector

Ever thought of selecting all elements on a web page? Well CSS developers did so, and consequently provided with the universal selector to serve this job.

It is denoted by an asterisk * and selects all elements on the entire HTML page or within a given selector. For now on we will consider the former only, since the latter requires you to understand CSS Combinators first.

/* Select ALL elements in the html page */
* {border: 1px solid red}
A div with a span.

A paragraph with a span

Another paragraph with bold text

Although it might seem exciting at this stage to be able to select everything using the universal selector, it is considered one of the bad practices in CSS. Why? Simply because it's way slower and inefficient than the other CSS selectors we saw earlier in this chapter.

As you get into CSS more and more, you'll find the use cases of this selector pretty low in number - people don't use it very often. However if you ever feel the need to use it to select all elements, in a given element, consider trying out other possibilities before proceeding with it. Always keep it for the worst case!

A combination of all these

Uptil now we have just seen individual selectors working on their own in the examples above. What if we want to select, let's say, a p element with class large and id first. With more than one selection filter to apply we will now need to combine our selectors. Let's see how to do it.

If we want to select a p element with id first we can simply write:

p#first {color: blue}

Here we first select all the p elements and from them, the one with id first. Notice the absense of space between the tag and id selectors above - no space indicates the selectors to be combined together in selecting elements.

Let's see more examples on these combination selectors:

Select all p elements with class large:

p.large {font-size: 16px}

Select the p element with class large and id first:

p.large#first {color: blue}

Select all p elements with class large and title "Hello":

p.large[title="Hello"] {font-size: 16px}

Select all p element that are the first children of their parent and in their hover state:

p:first-child:hover {color: blue}

And so on and so forth...

So therefore when we have NO space between selectors we have them combined together to select HTML elements. However if we have a space between selectors then we have what we call nested or descendant selectors.