Pseudo-classes

 




What are Pseudo-classes?

A pseudo-class is used to define a special state of an element.

For example, it can be used to:

  • Style an element when a user mouses over it
  • Style visited and unvisited links differently
  • Style an element when it gets focus

The syntax of pseudo-classes:


  selector:pseudo-class {
    property: value;
  }

Interactive states

  • pseudo-classes apply due to an interaction a user has with your page

:hover

  • For example: if the user hovers the mouse on the button then the style of the button changes.

:active

  • if the user clicks on the button then the style of the button should be in an active state.

:visited

  • if a user has already visited then it will show the visited state.

:focus, :focus-within, and :focus-visible 

  • If an element can receive focus—like a <button> you can react to that state with the : focus pseudo-class.

:target

  • :target pseudo-class selects an element that has an id matching a URL fragment. Say you have the following HTML:

<article id="content">

</article>

#content:target {

background: yellow;

}

Order matters:

  • If you define a  :visited style, it can be overridden by a link pseudo-class with at least equal specificity. Because of this, it's recommended that you use the LVHA rule for styling links with pseudo-classes in a particular order: :link,  :visited,  :hover,  :active.
    • a:link {}
    • a:visited {}
    • a:hover {}
    • a:active {}

:first-child and:last-child 
  • If you want to find the first or last item, you can use :first-child and :last-child. These pseudo-classes will return either the first or last element in a group of sibling elements.

:only-child
  • You can also select elements that have no siblings, with the :only-child pseudo-class.

:first-of-type and :last-of-type

  • You can select the :first-of-type and :last-of-type which at first, look like they do the same thing as :first-child and :last-child, but consider this HTML:


<div class="my-parent">
<p>A paragraph</p>
<div>A div</div>
<div>Another div</div>
</div>

.my-parent div:first-child {
color: red;
}

  • No elements would be colored red because the first child is a paragraph and not a div. The :first-of-type pseudo-class is useful in this context.

.my-parent div:first-of-type {
color: red;
}
  • Even though the first <div> is the second child, it is still the first of type inside the .my-parent element, so with this rule, it will be colored red.

:nth-child and :nth-of-type 

  • You're not limited to first and last children and types either. The :nth-child and :nth-of-type pseudo-classes allow you to specify an element that is at a certain index. The indexing in CSS selectors starts at 1.

0 Comments:

Post a Comment

Do leave your comments