::before

Term side of the Card.
Topic: Pseudo Elements
Unit title: ::before
Categories: Pseudo-element
Explanation side of the Card

Explanation: The pseudo-element used to insert content before the content of an element. It can be used to add decorative elements, such as icons or special symbols without changing the HTML structure.

Browser compatibility:
  • The chrome browser supports this feature starting from version 1.
  • The edge browser supports this feature starting from version 12.
  • The firefox browser supports this feature starting from version 1.5.
  • The safari browser supports this feature starting from version 4.
Availability: 

Example

Wrongcss
.external::before {
  width: 1em;
  height: 1em;
  background: url(icon.svg);
}
Rightcss
.external::before {
  content: '';
  display: inline-block;
  width: 1em;
  height: 1em;
  background: url(icon.svg);
}

Without content the pseudo-element isn't created, and as an inline box it ignores width and height.

Common mistakes

  • Nothing shows because the content property is missing.
  • Adding ::before to an <img> or <input>, where it doesn't render.
  • Setting width and height on an inline ::before, which ignores them.

Key points

  • Every ::before rule sets content, at least content: '', or nothing renders.
  • Essential text isn't placed in content, since generated text can't be selected or copied.
  • Pseudo-elements are used on elements that can have children, not on <img> or <input>.

Interview questions

Why is my ::before not showing?

Usually content is missing. Also check that the element can hold children, since <img>, <input> and other replaced elements don't render ::before.

Do screen readers read ::before content?

Often yes. Screen readers usually announce text from content, so decorative symbols can add noise.

What is the difference between :before and ::before?

None in behavior. The double colon is the current pseudo-element syntax; the single colon still works for compatibility.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy