Type Selectors

  • Selectors are used to determine which HTML element(s) get styled.
  • The most common type of selector is the type selector, which selects all matching elements on the page for styling. Example :
div {
  /* Styles go here. */
}

As shown above, whatever declarations we replace the comments with are applied to every div element in the connected HTML file.


Class and ID Selectors

If we want to get more specific, we can select elements by their HTML attributes.

The following example selects elements with a class of "class-name" or an id of "id-name":

.class-name {
  /* Styles go here. */
}
 
#id-name {
  /* Styles go here. */
}
  • Selecting by class is done with a . period, and used to style multiple elements with a matching class attribute.
  • Selecting by id is done with a # hashtag, and used to style a single element with a matching id attribute.

However, we can be even more specific:

div.class-name {
  /* Styles go here. */
}
 
div#id-name {
  /* Styles go here. */
}

Rather than selecting every element with a matching class or id, the example above selects only div elements that either have a class of "class-name" or an id of "id-name".

This specific kind of selection is also known as targetin


Grouping

As we dive further into CSS, we will begin to notice that we’re assigning the same styles to different elements.

For example, we may have the following CSS code:

ul {
  border: 1px solid;
  width: 50px;
}
 
ol {
  border: 1px solid;
  width: 50px;
}

As we add more styles to our page, our CSS may start to become repetitive and less readable.

We can group our styles together so we aren’t repeating ourselves:

ul, ol {
  border: 1px solid;
  width: 50px;
}

This way, we can apply a single rule to multiple elements at once!


Combining

We can also get more specific by using the > symbol to select child elements, such as only <li> elements under unordered lists:

ul > li {
  border: 1px solid;
  width: 50px;
}