Single-colons : designate pseudo-selectors.
Double-colons :: designate pseudo-elements.
Pseudo-selectors select elements that already exist on the page, like an :nth-child(2)
Pseudo-elements select a part of something for which there is no existing HTML element. Without a <span>
around the first letter that's targeted, the first letter is like a new element added to the page.
li:first-child { color: red; }
li:nth-child(1) { color: red; }
li:nth-child(2) {color: blue;}
class:nth-child(1) { color: red; }
class:nth-child(2) { color: blue; }
class:nth-child(3) { color: green; }
First paragraph of div
Second paragraph of div
Third paragraph of div
class:nth-child(1) { color: red; }
class:nth-child(2) { color: blue; }
class:nth-child(3) { color: green; }
Span - first child of paragraph. Span - second child of paragraph. Span - third child of paragraph.
td:nth-of-type(2) { color: blue; }
td:nth-of-type(3) { color: red; }
td:last-of-type { color: green; }
First | Table | Row | Last |
Second | Table | Row | Last |
Third | Table | Row | Last |
p:nth-of-type(2n+1) { color: blue; }
p:nth-of-type(2n) { color: red; }
Note: :nth-of-type(2n)
with (2n+1)
functions the same as :nth-child(odd), :nth-child(even)
First paragraph
Second paragraph
Third paragraph
:nth-child(2) { color: var(--secondary-color); background-color: var(--primary-color);
}
Parent
Child
subChild
:nth-child(odd){ color: var(--primary-color); background-color: var(--secondary-color); }
.alternating :nth-child(even){ color: var(--secondary-color); background-color: var(--primary-color); }
First
Second
Third
Fourth
This uses the ::before
pseudo-element to put a background image "before" and under the section element
::before {
content: "";
background:url("https://picsum.photos/1200/400");
background-repeat: no-repeat;
background-position: center;
background-size: cover; /* Resize the background image to cover the entire container */
opacity: 0.5;
top: 0;
left: 0;
bottom: 0;
right: 0;
position: absolute;
z-index: -1;
}
The heading above is created by just the word "Heading" with a ::before
element with the content "This" and an ::after
element with the content: "is created with pseudo-elements."
h2::before { content: "This "; }
h2::after { content: " is created with pseudo-elements."; }
The drop cap on the heading, is created by styling the ::first-letter
of the heading element. Since the ::before
is "before" the content not the element, the drop cap will be applied to the first letter whether it is created in the html or the css. The drop cap on this paragraph is created by the :first-child
pseudo-selector.
::first-letter { font-size: 4rem; float: left; font-family: serif; position: relative; }