Complete, Concrete, Concise

Practical information without the bloat

CSS – Selecting Specific Elements for Styling

We can be selective in which HTML elements we style.

So far, we have seen a few CSS style properties and how they can be applied to HTML elements. However, this way of styling affects all the HTML elements, it would be useful to selectively style certain p tags rather than all of them.

Contents

  1. CSS Selectors
    1. Type Selector
    2. ID Selector
    3. Class Selector
    4. Universal Selector
    5. Attribute Selector
  2. Conclusion
  3. Playing Around
  4. References

CSS Selectors

We’ve seen that CSS Styling has the following format:

selector {
  property-1: value;
  property-2: value;
  ...
  property-n: value;
}

The only selector we used was the HTML element type (p, h1, etc). There are five different types of selectors.

You can apply the same style to multiple selectors by listing them and separating them with commas:

selector-1, selector-2, ..., selector-n
{
  property-1: value;
  property-2: value;
  ...
  property-n: value;
}

This is commonly used to set default styles for various elements. For example, perhaps you want all heading items to have the same appearance, you could do it like this:

h1, h2, h3, h4, h5, h6 {
  color: blue;
  background-color:cornsilk;
}

Type Selector

This is the one you have already seen – the unadorned HTML element type:

h1, h2 {
  background-color: red;
}

ID Selector

We have seen that all HTML elements can have attributes. One attribute they can have is the id attribute – it is often used as a link reference for the a tag. The id is accessed by prefacing its value with the pound sign (#):

<h2 id="contents">Contents</h2>
...
<a href="#contents">Return to Contents</a>

You can use this id as a CSS Selector as well:

#contents {
  color: white;
  background-color: black;
}

The above code snippet will select the HTML element which has an id value of contents.

As a reminder, every id in a document must be unique.1

Class Selector

HTML tags can have another attribute called class. Classes do not have to be unique in the document. Several HTML elements can use the same class:

<p class="important">This is an important paragraph.</p>

The class definition is very similar to the id definition. The value should be composed of letters, digits, underscores, or hyphens. No spaces or other characters. It should begin with a letter or underscore, not a digit or hyphen.

To access a class and use it for styling, you need to preface the class name with a period (.):

.important {
  background-color: yellow;
}

The above code snippet will set to yellow the background colour of all HTML elements with the class of important.

You can apply multiple classes to the same HTML element by listing them and separating them with a space:2

<p class="c1 c2 c3">This is a sample paragraph.</p>

In the code snippet above, the classes c1, c2, and c3 will be applied to the paragraph. Consider the following class style definitions:

.c1 {
  color: blue;
}

.c2 {
  background-color: yellow;
}

.c3 {
  border: 2px black solid;
}

Applying the above classes to the HTML fragment above results in:

This is a sample paragraph.

It should be obvious that you should try to select meaningful names for your classes (just as you should for ids).

Your class names should reflect the purpose of the class, not its behaviour (there are always exceptions). For example, instead of calling a class red-bg, it might be better to call it alert or warning. Or instead of calling a class background it might be better to call it article-bg or header-bg.

I can’t stress enough how important it is to properly structure your HTML documents.

Having said that, you will probably never get it 100% right, but that doesn’t mean you shouldn’t try to get it as right as possible. A good trick is to imagine that in the future the document needs to be completely restyled. If you can simply change the styling in the class without having to change the class name, then you probably got it right. Consider the red-bg class in the previous paragraph – if you change it to blue then the class name no longer makes any sense. However, had it been warning, you can change the background colour all you want and it doesn’t affect the class name.

Universal Selector

Sometimes, you want to apply a particular style to all the elements on the page. This can be done using the universal selector:

* {
  margin: 5px;
}

The above code snippet will set the margin to 5 pixels for every single element in the document.

It is very powerful tends to be used different ways:

  1. To change the default behaviour of everything in the document. We’ll see an example of this in a future tutorial when we change the behaviour of the CSS Box Model.
  2. It is also useful for certain selection behaviour. This tutorial only covers basic selection. Future tutorials will explore more advanced selection.3

Attribute Selector

You can select HTML elements based on their attributes. The attribute name is enclosed in square brackets ([])

[reversed] {
  background-color: gray;
}

The above code snippet selects all HTML elements with the reversed attribute. It only tests if the attribute has been specified for the element, it doesn’t care about the value of the attribute.

You can also test for specific attribute values:

[start="10"] {
  background-color: yellow;
}

The above code snippet selects all HTML elements with a start attribute having the value of 10. Values must be enclosed in quotes (single or double quotes). The value must exactly match.

Instead of using class or id selectors, you could use attribute selectors for class or id. Consider the following:

Consider the following:

<style>
  [class="bob"] {
    color: blue;
  }

  [class="mary"] {
    background-color: yellow;
  }

  [class="bob mary"] {
    color: green;
    background-color: red;
  }

  [class="mary bob"] {
    color: red;
    background-color: green;
  }
</style>

<p class="bob">This is Bob.</p>
<p class="mary">This is Mary.</p>
<p class="bob mary">This is Bob and Mary.</p>
<p class="mary bob">This is Mary and Bob.</p>

}

The code snippet above is a non-standard way of styling using classes or ids – but it can be done (remember, just because something can be done, doesn’t mean it should be done). You have to exactly match the class value to style it. Had you styled the classes instead, then the styles combine and build one atop the other.

There are more ways to select using attributes, but we’ll cover those in a future tutorial.

Conclusion

  1. There are 5 different ways to select HTML elements for styling:
    1. Type
    2. ID
    3. Class
    4. * (universal)
    5. Attribute
  2. Type Selection uses the name of the HTML element type. E.g:
    h1 {
      color: red;
    }
  3. ID Selection uses the ID attribute of the HTML element. The id is prefaced with the pound sign (#). An HTML element can have only one id and the id must be unique in the document. E.g.:
    #table-of-contents {
      color: blue;
    }
  4. Class Selection uses the class attribute of the HTML element. The class name is prefaced with a period (.). Classes do not need to be unique in a document. You can apply several classes to an HTML element. E.g.:
    .notification {
      color: yellow;
      background-color: blue;
    }
  5. Universal Selection selects all HTML elements. E.g.:
    * {
      color: red;
    }
  6. Attribute Selection selects all elements matching the specified attribute. E.g.:
    [reversed] {
      color: black;
      background-color: white;
    }
  7. Most commonly, you will use classes for styling HTML elements.
  8. Choose good class names. In general, they should indicate the function of purpose of the styling, not its effect.

Playing Around

The best way to learn is to play around with what you have learned.

Some webpage ideas:

  1. Create a webpage with alternately styled paragraphs using classes:

    This is one paragraph.

    This is another.

    This is the third paragraph.

    After this, there is no other.

  2. Style ordered lists differently depending on whether or not the reverse attribute is set. Refresh your knowledge of the reverse attribute.
  3. Style hyperlinks differently depending on whether they open in the current tab, a new tab or initiate a download. Refresh your knowledge of hyperlink attributes.
  4. Try applying multiple classes to an element. What happens if two classes style the same property with different values?4 Does the order of the classes change anything?

Use the CSS properties you have learned so far and try multiple (and conflicting) combinations:

  • color
  • background-color
  • border
  • padding
  • margin

In the next tutorial, we will expand our vocabulary of CSS styling properties.

References

  1. Type Selector
  2. ID Selector
  3. Class Selector
  4. Universal Selector
  5. Attribute Selector

  1. If you have duplicate id tags in your document, the page will still load and render, but some functionality may be broken. For example, if you use the id as a reference to an anchor tag, which id will it jump to? It can’t jump to both.
  2. You might be wondering if you can have multiple different IDs on the same HTML element. The answer is no. You can have only one ID per element and each ID must be unique in the document:

    Historically elements could have multiple identifiers e.g., by using the HTML id attribute and a DTD. This specification makes ID a concept of the DOM and allows for only one per element, given by an id attribute. –W3C DOM 4.1

  3. Styling elements depending on their context. For example, you may style block quotes (the html tag is blockquote), differently if it appears in the main content than when it appears in a sidebar.
  4. On a big project, it is common to use multiple classes on an HTML element. You might style the same property differently in two different classes. Maybe the background-color in one class is aliceblue and cornsilk in another. How does the browser (user-agent) resolve that?