Selectors target HTML elements that we want to style with CSS. By associating our declarations with one (or many!) elements in our HTML document.
The 4 basic selectors are
An element selector will select an HTML element by name.
Using CSS we can select the
p element, and style it as we like.
Let’s say we want to give the text a red color.
Note that this rule will target all
p tags on our page. So if we have multiple paragraphs they’d all be changed to red.
When we want to style specific elements, we use
Every HTML element can have
id attributes applied. We use these attributes to target the element specifically.
And as we’ll see,
id's are both used in a similar manner, but there’s an important difference between the two:
The same class value is repeatable across many elements.
idmay only be used once.
- So we use
classeswhen we need to select an element with 2 or more specific
In our CSS, we prefix with the period
. symbol to denote a
class, and for
id’s we use the hash
The thing to remember is that id selectors are rigid and don't allow for reuse. A general rule of thumb when considering using an id is to first try to use a tag name, one of the new HTML5 elements, or even a pseudo-class.
This isn't considered good practice in production code, as it adds unnecessary weight.
So we’ve seen how to use a
class or an
id to target a given HTML element for styling with CSS.
Let’s take a look at how we can connect multiple selectors, for even more specific styling!
As we've seen, we can select all elements with a specific
id name and apply our style rules accordingly.
You can, in fact, target a specific element that has a given
For this, we use the element followed by
# (to denote class or id), followed by the
As we’ve now seen, we can select an element with a specific
. followed by the
class name. But it’s often the case that an element will have 2 (or more) classes.
We select such elements, by combining the
class names separated with a dot, without spaces.
Using the same method, you can select elements by combining a
class and an
We can also combine selectors to apply the same declarations to multiple selectors.
We do this by separating with a comma.
So here we’re grouping both
span elements together.
We can get even more specific by selecting elements according to how they sit in the document hierarchy.
Note: the space is necessary between the two elements
This selection will work regardless of how deeply our
span is nested. As it’s selecting any
span with a parent
So in this case, if a
span is not the first child of the
p element, it’s not going to have the styling applied.
We can also select adjacent siblings, that is an element only if it’s preceded by a specific element.
We do so using the
If you liked this post, make sure to follow me on Twitter where I post daily about Tech related things!