- Selectors are the perhaps the most important part of CSS syntax. They allow you to purposely target specific content and style it in a way that's unique to that element. By using selectors intelligently, you can write efficient CSS that styles your content with a minimal amount of code. CSS rule sets are comprised of two parts: the selector and the declaration block. Property value pairs are stored inside the declaration block, and are used to determine the styling that's applied to the content.
Without a selector, however, there's no way for a user agent to know where to apply the styling. So by understanding all of the different types of selectors available and how you can combine them, you can write CSS that styles your page as efficiently as possible. In this chapter we'll start by exploring the basic CSS selectors that will perform the bulk of your targeting needs. It's also helpful to understand exactly how selectors work within browsers. When a browser first encounters a webpage, it builds two things: the Document Object Model or DOM and the CSS Object Model.
The DOM is essentially a tree-like structure that describes the relationship of a page's elements to one another. The CSS Object Model breaks down any stylesheet content in a similar fashion with rules being described in a tree-like representation depending upon how the styles were authored. The CSS Object Model is then combined with the DOM and any user-specific preferences and then rendered in the browser. To construct the CSS Object Model, a browser must parse through all of the selectors in a stylesheet, and then group the styles in a tree-like fashion that is similar to the DOM.
Because CSS is render blocking, this step is critically important. Nothing will be rendered to the page until the CSS Object Model is created. This is one of the reasons that writing efficient CSS is so important as poorly written CSS can negatively affect performance. Later in the course we'll take a closer look at the efficiency of different selector types and some of the strategies that you can employ to increase the performance of your styles. For now as we start to focus on the individual selector types, keep in mind that writing efficient selectors makes it easier for browsers to construct the CSS Object Model and reduces the amount of time to render.
- Targeting classes and IDs
- Working with group selectors
- Targeting element attributes
- String matching
- Targeting links with pseudo-class selectors
- Targeting child elements and empty elements
- Targeting parent, child, and sibling elements
- Matching patterns
- Writing efficient selectors