Introduction
I've been a backend developer for a long time and decided that I want to learn more frontend skills. So, I've started doing 30 days of CSS. You can follow my progress on Twitter at @cloudblogaas
For my first couple of days, I've learned about selectors and selector specificity.
Selectors
For my reference, some of the more common selectors are:
Selector | Description |
---|---|
* | Selects all elements |
element | Selects all elements of type "element", e.g. h1, or p |
el1, el2 | Selects all elements of the specified type, e.g. h1, h2 |
el1 el2 | Selects all elements of type "el2" inside elements of type "el1", e.g. div p selects all "p" within "div" |
el1 > el2 | Selects all elements of type "el2" where "el1" is the direct parent, e.g. div > p selects all "p" with parents "div" |
.cls | Selects elements with the class "cls" |
.cls1.cls2 | Selects ellements with class "cls1" and "cls2", e.g. .task.information |
#id | Selects elements with the id "id" |
element.class | Selects elements of type "element" with class ".class", e.g. p.information |
There are many more selectors, all detailed at MDN WebDocs. The ones above though, seem to be the most common.
I've followed this video on YouTube which I found invaluable for learning.
Selector Specificity
Selector Specificity allows us to know what orders selectors will be used. This is useful when trying to work out what a style hasn't been applied to an element. Normally, CSS is read from the top of the file downwards, so something at the bottom of the css file will overwrite something defined at the top.
Selector specificity states how certain selectors are "higher priority" than others. The specificity of selectors ranks from high to low as:
- style
- id
- class
- element
So, for example if an element has the following css, the style associated with the id would be used instead of that of the class, so the element would be styled red.
#myId {
color: red;
}
.myClass {
color: blue;
}
<h1 id="myId" class="myClass>...</h1>
A style can be defined as important by appending the !important
tag, for example:
.myClass {
color: blue !important;
}
From what I've seen though this is considered bad practice as it breaks specificity and can override what a system is meant to do.
Summary
CSS wouldn't be CSS without selectors. The MDN WebDocs on Selectors and MDN WebDocs on Specificity provide good indepth details.
Top comments (0)