Chapter 1.3.1 - Selectors
Selectors
As elements are added to a web page, they may be styled using CSS. A selector designates exactly which element or elements within our HTML to target and apply styles (such as color, size, and position) to. Selectors may include a combination of different qualifiers to select unique elements, all depending on how specific we wish to be. For example, we may want to select every paragraph on a page, or we may want to select only one specific paragraph on a page. Selectors generally target an attribute value, such as an id or class value, or target the type of element, such as <h1> or <p>. In CSS, selectors are followed by curly brackets, { }, which hold the styling that is applied to the selected element. In the following example, the selector 'p' is used to tell CSS to apply specific styles to the <p> elements.
To code and upkeep professional websites, it is important that you know how to properly classify different elements and apply styles: selectors play a crucial role in this.
Type Selectors
Type selectors target elements by their element type. For example, if we wish to target all division elements, <div>, we would use a type selector of div. The following two code snippets showcase the CSS selection as well as the elements that are selected in the HTML file.
CSS
div { ... }
HTML
<div>...</div>
<div>...</div>
Class Selectors
Class selectors allow us to select an element based on the element’s class attribute value. Class selectors are a little more specific than type selectors, as they select a particular group of elements rather than all elements of one type.
Class selectors allow us to apply the same styles to different elements at once by using the same class attribute value across multiple elements.
>In CSS, classes are denoted by a leading period, ., followed by class attribute value. In the next example, the class sector selects any elements containing the class attribute value of awesome including both division and paragraph elements.
CSS
.awesome {...}
HTML
<div class="awesome">...</div>
<p class="awesome">...</p>
ID Selectors
ID selectors are even more precise than class selectors, as they target only one unique element at a time. Just as class selectors use an element’s class attribute value as the selector, ID selectors use an element’s id attribute value as a selector.
id attribute values can only be used once per page. Reserve them for significant elements!
In CSS, ID selectors are denoted by a leading has sign, #, followed by the
idattribute value. In the following example, the ID selector will only select the element containing theidattribute value ofoval.
CSS
#oval {...}
HTML
<div id="oval">...</div>
In the previous chapter we talked about HTML attributes like id and class but omitted what they were used for. Now you know that they're mostly used to link CSS to them (among other reasons)!