844 Tall Grass Lane; Mundelein, IL 60060 847-510-5987 info@spritzweb.com

Facebook Linked In Twitter YouTube
Spritz Logo

Pseudo-Classes

A pseudo-class is a specific characteristic of an element that can be targeted with CSS. A few common pseudo-classes are :link, :visited, :hover, :active, :first-child and :nth-child. Pseudo-classes are always preceded by a single colon (:) .

Selectors

Examples

li:last-child { color: orange; }


The :last-of-type pseudo-class represents the last element of its kind in its parent container. In the following example, the last li and the last span elements will be the only ones with orange text.

ul.pseudo2 :last-of-type { color: orange; }


Use Not to target all elements except a specific one. Can also string multiple instances together.

.pseudo3 li:not(:last-child) { color: purple; }


The :nth-child pseudo-class targets one or more elements depending on their order in the markup. All of the :nth pseudo-classes take an argument, which is a formula that we type in parentheses. The formula may be a single integer, a formula structured as an+b or the keyword odd or even.

ol :nth-child(2) { color: orange; } --Selects the 2nd child
ol :nth-child(2n) { color: orange; } --Selects every other child starting from the second one
ol :nth-child(even) { color: orange; } --Selects all even-numbered children

 

There are many more options - see link below for more information.


Pseudo-Elements

Pseudo-elements are like virtual elements that we treat like regular HTML elements. They are preceded by either a double colon (CSS3) or a single colon (for backwards compatibility). Just use single colons for now.

The new CSS3 way of writing pseudo-elements is to use a double colon --  a::after { … }, to set them apart from pseudo-classes. CSS3 however also still allows for single colon pseudo-elements for the sake of backwards compatibility, and we advise that you stick with this syntax for now.

A few common pseudo-elements are :after, :before and :first-letter.


The :before element, like its sibling :after, adds content (text or a shape) to another HTML element.

<h1>Richard</h1>

h1:before { content: "Hello "; }

 

The result is: Hello Richard


Adding content after an HTML element, using the ":after" element:

.after li { display: inline; margin-left:5px; }
.after li:not(:last-child):after { content: " | "; margin-left: 5px;}

Note that by combining the "not", "last-child" and "after" into 1 CSS rule, the pipe symbol isn't generated for the final list item.


For more info, see: https://www.smashingmagazine.com/2016/05/an-ultimate-guide-to-css-pseudo-classes-and-pseudo-elements/