Lesson 2.5. CSS selectors

Type selectors

When the syntaxe h1 is used in CSS, this is a type selector. It specifies that the style will be applyed to all the <h1> tags.

Internal style CSS syntax

Any HTML tag can be selected with this syntax, as an example:

/* Styling heading 1 */
h1 { text-align: center; }

/* Styling paragraphs */
p { color:red; }

You can select several tags separated by a comma:

/* Styling headings 1 and 2 */
h1, h2 { text-align: center; }

ID selectors

The ID selector (#myID) allows you to select tags with a given identifier. Remember that an identifier must be unique on the page. In CSS, this selector is defined by preceding the ID with an hashtag #:

/* Styling tag identified by myId */
#myId { color:red; }

Class selector

The class selector (` .myClass```) allows you to target all the tags belonging to a given class. A HTML class is defined with the attributeclass =" "`:

<div class="myCLass">Example of division belonging to the class 'urgent'</div>

The advantage of the class selector is to target tags of any types. This selector is defined by preceding the name of the class with a point. Here is an example :

/* Styling the class myClass */
.myCLass { color:red; }

The attribute selector

The attribute selector ([myAttribute]) makes it possible to target all the tags having a given attribute. The syntax is the name of the attribute between brackets:

/* Select every tag with the 'title' attribute */
[title] { color:red; }

The attribute selector ([myAttribute = myValue]) optionally allows you to specify a given value for this attribute. Here is an example :

/* Select every tag with the 'title' attribute with value 'cat' */
[title=cat] { color:red; }

The universal selector

The universal selector * target all the tags in the page:

/* Everything is in red */
* { color:red; }

Selectors combination

We will not go into details here, but it is possible to combine the selectors between them. The CSS syntax is very powerful and has many features. Here is an example of how to select all tags of type <a> having an attribute of type href =" " whose value starts with https: // lucidar.me:

a[href^="https://lucidar.me"] { color:red; }

The day you need this type of selector, you will find many websites explaining how to combine selectors.

Pick the right selector

Choosing a selector depends on many factors (page structure, developer habits, libraries used ...). The selection strategy comes with practice and experience. When possible, use selectors of type. If the latter is not appropriate, you should ask yourself the question of link between style and content. For basic layouts, the class selectors are frequently used.

See also


Last update : 03/10/2022