Pseudo-classes :short-explanation

Pseudo-classes :short-explanation

A short and simple explanation of pseudo-classes.

What is a Pseudo-class ?

A pseudo-class is a keyword that we add to the selector that specifies state of the selected element(s).

For example :

  • When the user hovers over the element - :hover can be used
  • When the input field is under focus - :focus can be used
  • When we want to target the first-child or last-child of any element - :first-child :last-child

Syntax :

selector:pseudo-class {
  /* Write your styles here */
}
  • selector == any HTML element <li>, <a>, <p> etc.
  • pseudo-class == :hover, :focus, :first-child, :last-child etc.

Example :

CSS snippet :

li:hover {
        background-color: orange;
        padding: 5px;
        border: 2px solid #000000;
}

HTML snippet :

...
<body>
<ul>
      <li>item1</li>
      <li>item2</li>
      <li>item3</li>
      <li>item4</li>
      <li>item5</li>
</ul>
</body>
...

In the above example, all the <li> elements will have an hover effect when the user hovers over them.

There are lot of pseudo-classes that we can make use in our projects :

  • :active
  • :any-link
  • :enabled
  • :fullscreen
  • :link
  • :nth-child()
  • and many more...

That's it for this blog. I hope you have learnt something from it.

Happy coding. Thank you !