CSS Selectors

There are basically 4 types of selectors and a combination of the 4.

  • Element Selector
  • Class Selector
  • ID Selector
  • Universal Selector

 CSS Element Selector

This selector selects HTML elements based on the element name.

For Example: <p>,<div>,<table>&<span>

So here is an example:

p {
color: blue;
text-align: left;
}

CSS Class Selector

The class selector selects HTML elements with a specific class attribute.

The class selector required a period (.) character, followed by the class name. You can have as many of the same class selectors on a page as you like.

So here is an example. The color of the text will be blue and left aligned:

.left {
color: blue;
text-align: left;
}

You can also specify an HTML element with a class.

So here is an example. The color of the text will be green and center aligned:

p.center {
color: green;
text-align: center;
}

HTML elements can also refer to more than one.
Ex: <p class=”center bold”> This is sample text</p>

So here is an example. Lets put it all together. Notice we are referring to 2 classes, both starting with a period (.) no spaces between them. This says p element that has both center and bold classes.

p.center.bold {
color: green;
text-align: center;
font-weight: bold;}

CSS ID Selector

The ID selector also selects HTML elements, but with a specific id attribute.

The class selector required a hashtag (#) character, followed by the ID name. You can only have the same ID once on a page. The id of an element is unique on a page, so the ID selector is used to select one unique element!

So here is an example of an ID selector:

#intropar {
color: green;
text-align: center;
}

CSS Universal Selector

The universal selector (*) selects all HTML elements on the page.

So here is an example. A rule that will effect ALL elements on a page

* {
color: green;
text-align: center;
}

Grouping Selectors

If you have the same styles to assign to different selectors, makes sense to group them to minimize on the code used. To group selectors, separate each selector with a comma (,) This can be classed, ID’s or Elements.

So here is an example. We are grouping all H elements, a class and an ID. These all are color green and centered.

H1, H2, H3, H4, .myclass, #myid {
color: green;
text-align: center;
}

Test It Yourself
Change the HTML and/or CSS on the left to see the RESULT on the right

See the Pen CSS Selectors by Ollie (@webocafe)on CodePen.