Open In App

How to apply style to parent if it has child with CSS?

We know how to apply styles to the child elements if a parent class has one. But if we want to apply a style to the parent class that with CSS. Here’s the way we can do that. A child combinator describes a parent-child between two elements. A child combinator is made of the “greater-than (>)” character and separates two elements.
Examples: 

.parent li {
    background:blue;
    color:black;
}
.parent > li > ul > li {
    background:orange
}

Program:






<!DOCTYPE html>
<html>
<head>
    <style>
        .parent li {
            background:blue;
            color:black;
        }
        .parent > li > ul > li {
            background:orange
        }
        .parent > li > ul > li > ul >li {
            background:pink;
        }
    </style>
</head>
  
<body>
    <ul class="parent">
        <li>I am first</li>
        <li>I am second</li>
        <li>I am third</li>
        <li>I am forth</li>
        <li>I am fifth
            <ul class="child">
                <li>child1</li>
                <li>child2
                    <ul>
                        <li>child2.1</li>
                        <li>child2.2</li>
                        <li>child2.3</li>
                    </ul>
                </li>
                <li>child3</li>
                <li>child4</li>
                <li>child5</li>
            </ul>
        </li>
        <li>I am sixth</li>
        <li>I am seventh</li>
        <li>I am eight</li>
    </ul>
</body>
</html>

Output:



CSS3 does not have parents selectors. If CSS4 released then there is a proposed CSS4 selector, $, which will be like selecting the li element.

ul $li ul.sub { ... }
$('ul li:has(ul.child)').addClass('has_child');

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.


Article Tags :