This post will describe:
- How to Style a Parent Element by Specifying its Child Elements?
- How to Select all Child Elements?
- How to Select all Direct Children Elements?
How to Style a Parent Element by Specifying its Child Elements?
First, create an HTML file having two “div” elements as follows:
- Add two “<div>” elements with the same class “parent-div”.
- The first one contains two “<p>” elements.
- The second “<div>” element contains “<h1>” and “<p>”:
If it is required to style the “<div>” element having the “<h1>” element, then we can adjust the styling of the parent element by holding the child. For this purpose, we can utilize the “:has()” selector.
From both of the “<div>” elements, select the one which contains the “<h1>” element using “.class-name:has(child-name)”:
background-color: #103e6d;
color: seashell;
width: 150px;
height: 150px;
border-radius: 50%;
text-align: center;
}
Here, we have applied the following CSS properties on the parent element:
- “background-color” is used to specify the element’s background color.
- “color” specifies the element text color.
- “width” is used to define the element width.
- “height” specifies the height of the element.
- “border-radius” property is used to set the rounded corners of the element.
- “text-align” specifies the text alignment.
Output
How to Select all Child Elements?
To select the child element with the help of the parent selector, go through the given example.
Example
Implement the following steps to create an HTML page:
- Add a div element that contains two “<p>” tags and a “<div>” tag having the class “child-div”.
- The child “div” element contains a “<p>” element:
We can select child elements through the parent “<div>” class. This will not only select its direct “p” elements but also selects the nested “p” elements:
background-color: #7F167F;
font-family: cursive;
font-size: 25px;
text-align: center;
color: whitesmoke;
}
Output
How to Select all Direct Children Elements?
To select the direct child of the parent div, we can use the “>” symbol. This will help to select all the “p” elements that are the direct child of parent “<div>”. For instance, we have applied the following CSS properties:
background-color: #7F167F;
font-family: cursive;
font-size: 30px;
text-align: center;
color: whitesmoke;
}
The “font-family” specifies the font of the selected element and “font-size” is used to define the size of the font:
Output
We have discussed about CSS parent selectors in HTML and CSS.
Conclusion
In CSS, the “:has()” selector is utilized as a parent selector pseudo-class. It is particularly used to select parent elements. For instance, “.parent-div:has(h1)” selects the parent element having the “<h1>” elements. In order to select the child element of the parent element, utilize “.parent-div p”. The condition statement can also be used to select all the direct child elements. This article has explained the CSS parent selector with examples.