Selectors
To understand how selectors work and their role in CSS, it’s important to know the parts of a CSS rule. A CSS rule is a block of code, containing one or more selectors and one or more declarations.
The most straightforward group of selectors target HTML elements plus classes, IDs, and other attributes which may be added to an HTML tag.
A universal selector—also known as a wildcard—matches any element.
A type selector matches a HTML element directly.
A HTML element can have one or more items defined in their
class
attribute. The class selector matches any element that has that class applied to it.
Notice how the
.
is only present in CSS and not the HTML. This is because the.
character instructs the CSS language to match class attribute members. This is a common pattern in CSS, where a special character, or set of characters, is used to define selector types.
Note: The value of a class attribute can be almost anything you want it to be. One thing that could trip you up, is that you can’t start a class (or an ID) with a number, such as
.1element
. You can read more in the specification.
An HTML element with an
id
attribute should be the only element on a page with that ID value. You select elements with an ID selector like this:
Note: If the browser encounters more than one instance of an
id
it will still apply any CSS rules that match its selector. However, any element that has anid
attribute is supposed to have a unique value for it, so unless you’re writing very specific CSS for a single element, avoid applying styles with theid
selector as it means you can’t re-use those styles elsewhere.
You can look for elements that have a certain HTML attribute, or have a certain value for an HTML attribute, using the attribute selector. Instruct CSS to look for attributes by wrapping the selector with square brackets (
[ ]
).
[data-type=‘primary’] { color: red;
}