CSS Pseudo Elements
What are Pseudo-Elements?
A CSS pseudo-element helps to make certain parts of an element look different.
Here's how it can be used:
- Change the appearance of the initial letter or the opening line of an element.
- You can add stuff before or after what's already in an element.
Syntax
The way you write pseudo-elements:
property: value;
}
The ::first-line Pseudo-element
The ::first-line
part is used to make the first line of text look different.
Here's an example that styles the opening line of text within all <p> elements:
Note: The ::first-line
part can only work with block-level elements, not others.
The following properties apply to the ::first-line
pseudo-element:
- font properties
- color properties
- background properties
- word-spacing
- letter-spacing
- text-decoration
- vertical-align
- text-transform
- line-height
- clear
The ::first-letter Pseudo-element
The ::first-letter
is a tool to make the first letter in a text look different.
Here's an example that changes the appearance of the initial letter in the text inside all <p> elements.
Note: The ::first-letter
special part can only be used with block-style elements.
The ::first-letter pseudo-element has these properties:
- font properties
- color properties
- background properties
- margin properties
- padding properties
- border properties
- text-decoration
- vertical-align (only if "float" is "none")
- text-transform
- line-height
- float
- clear
Pseudo-elements and HTML Classes
You can use pseudo-elements along with HTML classes.
Multiple Pseudo-elements
You can also put together multiple pseudo-elements..
In this example, we'll make the first letter of a paragraph red and very big. The remaining part of the first line will be blue and in small capital letters. The rest of the paragraph will be in the normal size and color.
Example
color: #ff0000;
font-size: xx-large;
}
p::first-line {
color: #0000ff;
font-variant: small-caps;
}
CSS - The ::before Pseudo-element
The ::before
thingy can add stuff in front of an element's content.
In this example, we place a picture in front of every <h1> heading on a webpage.
CSS - The ::after Pseudo-element
The ::after
pseudo-element can be used to insert some content after the content of an element.
The following example inserts an image after the content of each <h1> element:
CSS - The ::marker Pseudo-element
The ::marker
pseudo-element is used to choose the markers that appear alongside list items.
This example changes how the bullets or numbers look in a list.
CSS - The ::selection Pseudo-element
The ::selection
part is for highlighting what a user picks in an element.
You can use these CSS properties on the ::selection
:
color
,
background
, cursor
, and outline
Here's an example that turns the text you choose into the color red while putting it on a yellow background: