Code Highlights logo

Learn

Selectors

Pseudo elements & classes

Pseudo-classes and pseudo-elements are used to refine style rules in CSS and target elements under certain conditions. In other words, they allow you to style parts of an element rather than an entire element.

Pseudo-Classes

Pseudo-classes are used to select and style a specific state of an element. For example, styling the link when it's being hovered. Here are a few examples:

:hover

The :hover pseudo-class is used to apply styles to an element when a user hovers over it.

1a:hover {
2 color: blue;
3}

:active

The :active pseudo-class is used to apply styles to an element that is being activated or clicked on.

1.button:active {
2 background-color: gray;
3}

:focus

The :focus pseudo-class is used to apply styles to an element that has focus. For example, a form field that a user is currently filling out.

1form input:focus {
2 border: 2px solid red;
3}

:nth-child

The :nth-child() pseudo-class is used to select an element based on its position in a parent element.

1li:nth-child(odd) {
2 background-color: lightgray;
3}

Pseudo-Elements

Pseudo-elements are used to style a specific part of an element. For example, adding a triangle to the top of a speech bubble. Here are a few examples:

::before and ::after

The ::before and ::after pseudo-elements are used to insert content before and after an element.

1p::before {
2 content: "Quotation:";
3 font-style: italic;
4}

::first-letter and ::first-line

The ::first-letter and ::first-line pseudo-elements are used to style the first letter or first line of an element.

1p::first-letter {
2 font-size: 2em;
3 color: red;
4}
5
6p::first-line {
7 font-weight: bold;
8}

::selection

The ::selection pseudo-element is used to apply styles to the portion of an element that is selected by the user.

1p::selection {
2 background-color: blue;
3 color: white;
4}

Pseudo-classes and pseudo-elements are a powerful tool in CSS, allowing you to take your styling to the next level.


Instructions

1.

Add a ruleset to the end of style.css that selects the <a> elements on the page. Leave the declaration block empty for now.

2.

Next, add a :hover pseudo-class to the a selector you just created.

3.

Lastly, set the text color to pink by adding the following CSS declaration inside the declaration block:

1color: pink;

Now when you hover the mouse over the links, the font color changes to pink!

Sign up to start coding

Already have an account?

Sign In

Course content