Apply style to the parent class if it has a child with CSS and HTML

In this tutorial, we will learn how to apply style to the parent class if it has a child with CSS and HTML? By Shahnail Khan Last updated : July 11, 2023

Introduction

In HTML, we can easily style child class by using .class and #id selectors in CSS. What if we want to style parent class like Is it possible to style parent class elements that already have child class elements? Definitely Yes. The element > element selector serves this purpose. Let's understand this in detail.

What is element > element selector?

It's a selector in CSS which is used to target child class elements of a specific parent class. In element > element selector, ">" refers to child combinators The element to its right refers to child class element whereas the element to its left refers to parent class element. For example- Selector span>h2 targets all <h2> elements where the parent class is <span> only.

Syntax to apply style to the parent class if it has a child

element > element {
    // right element is child element; 
    // left element is parent element
}

Note: This selector is only available in CSS2 right now.

Example to apply style to the parent class if it has a child

Let's code to style our parent class if it has a child with CSS

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>
   </head>
   
   <style>
      .parent {
      background: blueviolet;
      color: black;
      font-size: large;
      width: 60%;
      }
      .parent > span > p{
      background: salmon;
      padding: 30px;
      }
      .parent > p {
      background: yellow;
      font-size: xx-large;  
      }
      .child > ul> p{
      border: 4px solid black;
      background-color: aqua;
      }
   </style>
   
   <body>
      <div class="parent">
         <p>This is the parent class</p>
         <div class="child">
            <ul class =" child1">
               <h2>Parent class can have many child classes</h2>
               <p>This is the first child class </p>
            </ul>
            <ul class="child2">
               <p>This is the second child class</p>
            </ul>
         </div>
      </div>
   </body>
</html>

Output

Apply style to the parent class if it has a child | Output

We have created one parent class with one child class that further has three child classes. We have used three-element > element selectors which serves a different purpose. In the ". parent > span> p" selector, span is the child element of parent class and p is the child element of span. In the same way, you can identify the parent and child class elements for the other two selectors.

CSS Examples »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.