Sobes.tech
Junior

What CSS pseudo-elements do you know and use?

sobes.tech AI

Answer from AI

  • ::before — inserts content before the element's content.
  • ::after — inserts content after the element's content.
  • ::first-line — applies styles to the first line of a block element.
  • ::first-letter — applies styles to the first letter of a block element.
  • ::selection — applies styles to the highlighted text.
  • ::placeholder — applies styles to placeholder text in input fields (<input>, <textarea>).
  • ::marker — applies styles to list markers (<li>).
  • ::backdrop — applies to the element behind a <dialog> or full-screen/modal element.
  • ::cuetext — applies to displayed subtitle or hidden caption text.
  • ::part() — allows styling internal elements of a shadow DOM component marked with the part attribute.
  • ::slotted() — allows selecting and styling elements inserted into shadow DOM via <slot>.

Most frequently used are ::before, ::after, ::first-line, ::first-letter, ::selection, ::placeholder, ::marker. ::backdrop and ::part()/::slotted() are used when working with custom elements and modal windows.

Example of using ::before and ::after:

/* Adding an icon before a link */
a::before {
  content: url('icon.png');
  margin-right: 5px;
}

/* Adding a decorative line after a header */
h2::after {
  content: '';
  display: block;
  width: 50px;
  height: 2px;
  background-color: blue;
  margin-top: 5px;
}

Example of using ::first-line and ::first-letter:

/* Styling the first line of a paragraph */
p::first-line {
  font-weight: bold;
}

/* Styling the first letter of a paragraph */
p::first-letter {
  font-size: 2em;
  color: red;
}

Example of using ::selection:

/* Styling selected text */
::selection {
  background-color: yellow;
  color: black;
}

Example of using ::placeholder:

/* Styling placeholder text */
input::placeholder {
  color: gray;
  font-style: italic;
}

Example of using ::marker:

/* Styling list markers */
li::marker {
  color: green;
  content: '🔥 '; /* Using emoji as marker */
}