CSS Pseudo Elements

Without changing the HTML file, the CSS pseudo elements allow us to apply specific properties on targeted elements. By default, the pseudo elements are inline elements. If we want to have padding and margin effect on them, we need to change the display property.

The common pseudo elements include :before:after:hover:focus and :nth-child. We can check out some examples for these popular pseudo elements.

  1. :before and :after

In the above example, I add text in the div element in CSS with the pseudo elements. In fact, we can insert image or add special characters just by changing the content value. Another common use of :after is to clear the floats, which will force the parent element to expand after the element’s content, but still inside the parent container.

2. :hover

:hover is useful when we want to apply different style on an element when the pointer is over it. It doesn’t have to be used with links.

3. :first-child, :first-of-type, :last-child, :last-of-type

The :first-child pseudo-class represents the first child of its parent element; The :last-child pseudo-class represents the last child element in its parent container.

The :first-of-type pseudo-class represents the first element of its kind in its parent container; The :last-of-type pseudo-class represents the last element of its kind in its parent container.

From the example, note that we append the :first-child and :last-child after the elements li, while we append the :first-of-type and :last-of-type after the parent elements ul in order to have the desired effect.

4. :nth-child or :nth-of-type

:nth-child is a versatile pseudo element in CSS. The difference of :nth-of-type is that we target a more specific element contained within the same parent element. The example is like below:

Oftentimes we will also see the (an+b) structure, such as (2n+1), meaning that “Select every other child starting with the first”. This is why :nth-child pseudo elements are so helpful, they target one or more elements on their order.

More information about pseudo-elements: https://www.smashingmagazine.com/2016/05/an-ultimate-guide-to-css-pseudo-classes-and-pseudo-elements/#first-of-type