CSS Selector Notes
- Staff Curator
- Web
- 15 Feb, 2020
- 20 Feb, 2020
- 8 min read
CSS (SCSS) applies dynamic rules to html elements and with that it follows certain rules and principles. Here, we’ll discuss different selectors to apply those rules and what order those will be applied.
Style Sheet Hierarchy
From general to specific. Items lower in the list will override items above them:
- Browser default settings
- User style settings (set in a browser as a “reader style sheet”)
- Linked external style sheet (added with the link element)
- Imported style sheets (added with the @import function)
- Embedded style sheets (added with the style element)
- Inline style information (added with the style attribute in an opening tag)
- Any style rule marked !important by the author
- Any style rule marked !important by the reader (user)
Specificity
Specificity is very important along with hierarchy to understand, how CSS rules are applied. Following is the simple list of selector types from most to least specific:
- ID selectors are more specific than (and will override)
- Class selectors, which are more specific than (and will override)
- Contextual selectors, which are more specific than (and will override)
- Individual element selectors
Example for specificity
p {
line-height: 1.2em;
}
blockquote p {
line-height: 1em;
}
p.intro {
line-height: 2em;
}
In this example, p elements that appear within a blockquote have a smaller line height than ordinary paragraphs. However, all paragraphs with a class of “intro” will have a 2em line height, even if it appears within a blockquote, because class selectors are more specific than contextual selectors.
Child and Descendant Selectors
Rather we should say direct children (Child) and all children (child in subsequent hierarchy)
Child
In CSS element > childElem represents a relationship of parent and direct child. element is parent and childElem is direct child. Style defined using these selector would apply to only direct child elements.
In SCSS, you can use the hierarchy to represent the same relation as shown below:
element {
//styles
> childElem {
// styles
}
}
Descendant
In CSS element childElem represents a relationship of parent and descendant. element is parent and childElem is child. Style defined using these selector would apply to both direct child elements or descendants.
In SCSS, you can use the hierarchy to represent the same relation as shown below:
element {
//styles
childElem {
// styles
}
}
Child and descendant with CSS class
Both above rules are also applicable in classes for e.g. .parent > .child and .parent .child. However, if you have both rules in place, you should write .parent .child before .parent > .child to make it applicable. This is because of Rule Order, according to which, what ever comes last wins. If you don’t follow the order in this case in the example given below direct paragraph would be displayed in brown instead of black.
There is special case .parent.child that would only work if any html element has both these class added to it. Order does not matter. For e.g. <div class="parent child">
To generate .parent.child in SCSS, you can write in following way:
.parent {
//styles
&.child {
// styles
}
}
Example
Please add the following code in codepen or any other web tool to see how it works.
<div class="par">
<p class="child">direct paragraph</p>
<div>
<p class="child">2nd gen paragraph</p>
</div>
<blockquote>
<p class="child par">blockquote paragraph</p>
</blockquote>
</div>
<div>
<p>direct paragraph</p>
<div>
<p>2nd gen paragraph</p>
</div>
<blockquote>
<p>blockquote paragraph</p>
</blockquote>
</div>
div p {
font-size: 18px;
color: red;
}
div > p {
font-size: 24px;
color: blue;
}
.par .child {
font-size: 36px;
color: brown;
}
.par > .child {
font-size: 36px;
color: black;
}
.par.child {
font-size: 36px;
color: green;
}
Sibling Selector
Adjacent Sibling Selector
An adjacent sibling selector targets an element that comes directly after another element with the same parent. It is indicated with a plus (+) sign. This rule gives special treatment to paragraphs that follow an h1. Other paragraphs are unaffected.
h1 + p {
font-style: italic;
}
General sibling selectors
A general sibling selector selects an element that shares a parent with the specified element and occurs after it in the source order. They do not need to follow one another directly. This type of selector is new in CSS3 and is not supported by Internet Explorer 8 and earlier. The following rule selects any h2 that both shares a parent element (such as a section or article) with an h1 and appears after it in the document.
h1 ~ h2 {
font-weight: normal;
}
& in SCSS
In SCSS, you can represent current selector using &. We have used & in above scss code snippet to apply the effect of .parent.child selector that would apply only if both parent and child classes are present.
However, when you have multiple hierarchal level of selector, you would like to store the current selector to apply to any n-level child selector as shown below:
.parent {
this: &;
&-div {
display: block;
&:hover,
#{this}-alt-active {
background-color: yellow;
}
&-alt-active {
background-color: green;
}
}
}
Here, it generates the two type of *-alt-active classes - parent-alt-active and parent-div-alt-active. parent-alt-active is using the stored this reference. Another one parent-div is using current selector (& = parent), which is concatenated to -div because &-div is used in scss.
.parent-div {
display: block;
}
.parent-div:hover,
.parent-div .parent-alt-active {
background-color: yellow;
}
.parent-div-alt-active {
background-color: green;
}
Attribute Selector
This type of selector applies based on attribute or attribute’s value. Attribute syntax is pretty simple: element[attribute] or element[attribute="attr value"].
Examples:
/* Applies to any image having a title */
img[title] {
border: 3px solid;
}
/* Applies to any image having a title attribute with exact string "sample" as value
(exact match) */
img[title="sample"] {
border: 3px solid;
}
/* Applies to any image having a title attribute with "sample" in its value
(partial match) e.g. "logo sample"*/
i*g[title~="sample"] {
border: 3px solid;
}
/* Applies to any element having a hreflang attribute with "en-" in its value
(hyphen value match) e.g. "en-us", "en-in" etc.*/
**hreflang|="en"] {
border: 3px solid;
}
/* Applies to any image having a src attribute starts with "/images/icons" in its value
(start string match) e.g. <img src="/images/icons…> etc.*/
img[src^="/images/icons"] {
border: 3px solid;
}
/* Applies to any image having a src attribute ends with ".png" in its value
(end string match) e.g. <img src="/images/articles/article.png> etc.*/
img[src$=".png"] {
border: 3px solid;
}
/* Applies to any image having a title attribute contains "company" irrespective of its place.
(arbitory substring match) */
img[title*="company"] {
border: 3px solid;
}
Pseudo Classes
Certain states are managed by the browsers like visited, active, hover for links, first child, last child of elements etc.
You can style that state using the pseudo classes. These are marked with :, like <selector>:<pseudo class>. For e.g. a:visited, section:firstChild etc.
Few common Pseudo Classes:
| Pseudo Class | Usage |
|---|---|
| :link | Applies to unvisited links |
| :visited | Applies to visited links |
| :focus | Applies when element is selected and ready for input |
| :hover | Applies when mouse is roll over an element |
| :active | Applies when element is in process of being clicked or tapped |
| :not() | Applies to all elements except the one in bracket for e.g. p:not(Class) applies to all p elements which don’t have the class attribute. |
There are bunch of others. Visit MDN web docs for pseudo classes for others.
Pseudo Elements
These are pseudo selectors like pseudo classes. Adds fictional elements into document. These are indicated with ::.
Few common Pseudo Classes:
| Pseudo Elements | Usage |
|---|---|
| :first-line | Applies to first line of element |
| :first-letter | Applies to first letter of elements, how many articles shows first letter in big size in capital letter |
| :before/:after | Applies to before and after the elements respectively. Common use case to insert icons to elements like search box with search icon. |
There are bunch of others. Visit MDN web docs for pseudo elements