How to make a parent selector in CSS

Overview

In CSS, we use the selector to select some specific element(s) from all the existing elements. We then style these element(s) according to our requirements.

We don’t have the feature of a parent selector, but we can achieve this in two ways:

  • Use level 3 specs for selectors

  • Use specs for current CSS selectors

Syntax for level 3 specs

<body>
<div class="Login">
<img alt="img" src="path of the image">
</div>
</body>
.page div
{
property: value;
}
.page div img
{
property: value;
}

Syntax for current CSS selectors

.nav-link::parent
{
property: value;
}

Example

The following code shows how to implement the CSS parent selector.

Explanation

HTML

  • Lines 1-9: We create a heading, and then some content is written in the div. Next, we call the parent and selector class.

CSS

  • Line 1-6: We set the parent class’s height, width, and background color.

  • Line 7-19: We set the properties of the parent and selector class and defining the background color.

  • Line 20-45: We set the properties so that when we move the cursor to the child element, then the background color of the parent changes.

Free Resources