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 and 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:
- E > F, an F element child of an E element.
- The following selector represents a “p” element that is child of “body”:body > p.
- So the style In the parent class can be by just writing the name once like this
.parent li { background:blue; color:black; }
- If we want to apply the style in child class then use this
.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 eigth</ li > </ ul > </ body > </ html > |
chevron_right
filter_none
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.
- However, as of now, this code can’t be used in any of the browsers.
ul $li ul.sub { ... }
- In the meantime, we’ll have to use JavaScript if we need to select a parent element.
$('ul li:has(ul.child)').addClass('has_child');