CSS-Pseudo

Home / CSS / CSS-Pseudo

CSS-Pseudo


CSS-Pseudo:

In CSS, pseudo-classes and pseudo-elements are used to select and style elements based on various states and positions that can't be targeted with simple selectors alone. They are denoted by a colon : and can be applied to existing selectors. Here's an overview of some common pseudo-classes and pseudo-elements:

Pseudo-classes:

:hover: Selects an element when the mouse pointer is over it.

 
<style>
    a:hover {
      color: red;
    }
  </style>

:active: Selects an element when it's being activated, typically when clicked on.

 
<style>
    button:active {
      background-color: green;
    }
  </style>

:focus: Selects an element when it gains focus, often used for form elements.


<style>
    input:focus {
      border-color: blue;
    }
  </style>

:not(): Allows you to select elements that do not match a specific selector.

 
<style>
    p:not(.special) {
      color: gray;
    }
  </style>

:first-child: Selects the first child of a parent element.

<style>
    li:first-child {
      font-weight: bold;
    }
  </style>

:last-child: Selects the last child of a parent element.

<style>
    div>p:last-child {
      margin-bottom: 0;
    }
  </style>

:nth-child(): Selects elements based on their position within a parent element.

 
<style>
    li:nth-child(odd) {
      background-color: lightgray;
    }
  </style>

Pseudo-elements:

::before and ::after: Create virtual elements before or after the content of an element.

<style>
    p::before {
      content: "➤";
    }
  </style>

::first-line: Selects the first line of text within an element.

<style>
    p::first-line {
      font-weight: bold;
    }
  </style>

::first-letter: Selects the first letter of text within an element.

 
<style>
    p::first-letter {
      font-size: 150%;
    }
  </style>

::selection: Allows you to style the portion of text that is selected by the user.

<style>
    ::selection {
      background-color: yellow;
      color: black;
    }
  </style>

::placeholder: Styles the placeholder text in input and textarea elements.

 
<style>
    input::placeholder {
      color: gray;
    }
  </style>