Selectors in CSS

Selectors in CSS

ยท

3 min read

This article is a continuation of my previous article which you can read here. In the previous article, we discussed the following selectors:

  1. Type Selector
  2. Universal Selector
  3. Class Selector
  4. ID Selector
  5. Attribute Selector

Let's discuss some more selectors in this article. This article focuses on another two selectors which are:

  • Pseudo-class
  • Pseudo-element

Pseudo-class

Pseudo class selectors are the selectors which start with the colon (:) sign. These are applied when a certain condition appears.

For example,

  • style an element when it is hovered,
  • change the color of an element when it is clicked and so on.

The syntax goes like this:

selector:pseudo-class {
      property:value;
}

Considering the syntax, let us suppose we want to change the color of all the paragraph to red when we hover it then we can do this

p:hover {
    color: red;
}

Some common pseudo-selectors are as below:

  • :link: Selects all the anchor tags which are not yet clicked. Say, in a normal state.

  • :visited: Selects those links which have been visited.

  • :hover: Works when certain element is being hovered.

  • :active: Works when we click a certain element, may be a link.

  • focus: Mainly used for styling inputs when clicked.

There is a huge list of pseudo-selectors. You can refer MDN for whole list.

Refer to this awesome article to know some practical applications of pseudo classes.

Pseudo-element

Pseudo-elements are used to style a specific part of an HTML element.

Some use cases for pseudo-elements are:

  • style the first letter of a paragraph.
  • insert some content before or after an element without changing the HTML.

Initially, pseudo-elements also used single colon(:) but this way it was difficult to differentiate between pseudo-classes and pseudo-elements.

Hence to differentiate CSS3 brought a new convention of using :: for pseudo-elements.

However, we can still use : for pseudo-elements but it is much better to stick according to the convention, right?

The syntax of pseudo-element:

selector::pseudo-element {
  property: value;
}

Using pseudo-element, we can increase the font-size and change the color of the first letter of a paragraph without affecting the whole paragraph in this way

p::first-letter {
  font-size: 64px;
  color: hotpink;
}

HTML

<p>Lorem ipsum has become the industry standard for design mockups and prototypes.</p>

OUTPUT

FIRST-LETTER.png

Some commonly seen pseudo-elements:

  • ::after
  • ::before
  • ::first-letter
  • ::first-line
  • ::marker
  • ::selection

You can refer these resources to know/practice the practical applications of pseudo-elements.

This is it. Thank you for reading. Feedbacks are appreciated ๐Ÿ˜๐Ÿ˜๐Ÿ™‹โ€โ™‚๏ธ๐Ÿ™‹โ€โ™‚๏ธ

I will be back soon with another article.

Until then, goodbye ๐Ÿ‘‹. May this year bring to you lots of wonderful surprises ๐ŸŽ๐ŸŽ and happiness.