In this answer, we will learn how to apply style to a parent class that has a child class with CSS.
It’s easy to apply style to a child element, but if you want to apply style to a parent class that already has child elements, you can use the CSS selector child combinator (>
), which is placed between two CSS selectors.
For example,
div > p
selects all <p>
elements where the parent is a <div>
element.
selector1 > selector2{
style code
}
selector1
is the parent element and selector2
is the child element.
In the example above:
In lines 9–12, we use the child combinator (>
) to define a child style div2
.
In lines 20–28, the parent div
is using the .div1
style and the child div
is using the .div2
style. You can see in the “Output” tab that the style of .div1
is modified by the style of .div2
.
The div
element in lines 30–32 doesn’t reflect the style of the .div2
class because it has no parent element.
The div
element in lines 36–40 is a child but it doesn’t reflect the style of the .div2
class. It is because the .div1
style is not applied on the parent div
in lines 32–42.
Note: The style can also be applied in a CSS file which will then have to be linked to the HTML file. However, this applies to immediate children. For nested children, we’ll have to use the descendant combinator.
7*: Before Internet Explorer 10, the combinator only works in standards mode.
Free Resources