Types of Selectors in CSS

Selectors can be grouped into four basic types: simple, compound, combinator, and complex.

Simple selectors are the oldest form of CSS selector, and may be the type used most often. Simple selectors specify a single condition for matching elements. The universal selector ( * ) is a simple selector. So are type (or element) selectors such as p and pseudo-element selectors such as ::first-Letter . Attribute selectors such as [hidden] , class selectors such .message-error , and ID selectors such as #masthead also fall into this category.

Compound selectors, such as p:last-child or .message.error , are a sequence of simple selectors that reflect a set of simultaneous conditions to meet when applying rules to an element. In other words, .message.error will match <div class=”message error”> , but not <div class=”message”> or <div class=”error”> .

Combinator selectors express a relationship between elements. There are four:

  • the descendant combinator, as in article p
  • the child combinator ( > ), as in .sidebar > h2
  • the adjacent sibling combinator ( + ), as in ul + p
  • the general sibling combinator ( ~ ), as in p ~ figure

Rules are applied to the right-most element in a combinator selector when it fits the condition indicated by the combinator. We’ll discuss combinator selectors in detail later in the chapter.

Lastly, there are complex selectors. Complex selectors consist of one or more compound selectors separated by a combinator. The selector uL:not(.square) > a[reL=externaL] is an example of a complex selector.

Selectors can be grouped into what’s known as a selector list by separating them with a comma. Selector lists apply styles to elements that match any of the selectors in the list. For example, the rule article, div { padding: 20px; } adds 20 pixels of padding to both <articLe> and <div> elements.

Knowing what kind of selectors you’re working with will help you grasp one of the more confusing aspects of CSS: specificity. Keeping specificity low increases the reusability of your CSS rules. A selector such as #menu > .pop-open means that you can only use the .pop- open pattern when it’s a direct descendant of #menu , even if there are similar interactions elsewhere in your project.

We’ll return to specificity in Chapter 2, “CSS Architecture and Organization”. For the rest of this chapter, however, we’ll discuss specific groups of selectors: combinators, attribute selectors, pseudo-elements, and pseudo-classes.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *