Pseudo-Elements

Other topics

Remarks:

  • Sometimes you will see double colons (::) instead of just one (:). This is a way to separate pseudo-classes from pseudo-elements, but some older browsers like Internet Explorer 8 only supports single colon (:) for pseudo-elements.

  • One can use only one pseudo-element in a selector. It must appear after the simple selectors in the statement.

  • Pseudo-elements are not a part of the DOM, therefore are not targetable by :hover or other user events.

Pseudo-Elements

Pseudo-elements are added to selectors but instead of describing a special state, they allow you to style certain parts of a document.

The content attribute is required for pseudo-elements to render; however, the attribute can have an empty value (e.g. content: "").

div::after {
  content: 'after';
  color: red;
  border: 1px solid red;
}

div {
  color: black;
  border: 1px solid black;
  padding: 1px;
}

div::before {
  content: 'before';
  color: green;
  border: 1px solid green;
}

Result of code

Pseudo-Elements in Lists

Pseudo-elements are often used to change the look of lists (mostly for unordered lists, ul).

The first step is to remove the default list bullets:

ul {
  list-style-type: none;
}

Then you add the custom styling. In this example, we will create gradient boxes for bullets.

li:before {
  content: "";
  display: inline-block;
  margin-right: 10px; 
  height: 10px;
  width: 10px;
  background: linear-gradient(red, blue);
}

HTML

<ul>
   <li>Test I</li>
   <li>Test II</li>
</ul>

Result

Result

Syntax:

  • selector::pseudo-element {property: value}

Parameters:

pseudo-elementDescription
::afterInsert content after the content of an element
::beforeInsert content before the content of an element
::first-letterSelects the first letter of each element
::first-lineSelects the first line of each element
::selectionMatches the portion of an element that is selected by a user
::backdropUsed to create a backdrop that hides the underlying document for an element in the top layer's stack
::placeholderAllows you to style the placeholder text of a form element (Experimental)
::markerFor applying list-style attributes on a given element (Experimental)
::spelling-errorRepresents a text segment which the browser has flagged as incorrectly spelled (Experimental)
::grammar-errorRepresents a text segment which the browser has flagged as grammatically incorrect (Experimental)

Contributors

Topic Id: 911

Example Ids: 3029,12381

This site is not affiliated with any of the contributors.