Friday, January 25, 2019

html - Apply style to parent if it has child with css




I'm trying to apply styles to the parent if it has child elements.



So far, I've applied styles to the child elements if present. But I want to style the parent if the parent has child, using ONLY CSS.




following is the html




  • aaaa

  • aaaa

  • aaaa

  • aaaa

  • aaaa

    • bbbb


    • bbbb

      • cccc

      • cccc

      • cccc



    • bbbb

    • bbbb

    • bbbb




  • aaaa

  • aaaa

  • aaaa




the css code




* {
margin:0;
padding:0;
text-decoration:none;
}
.main li {
display:inline-block;
background:yellow;
color:green;
}

.main > li > ul > li {
background:orange
}
.main > li > ul > li > ul >li {
background:pink;
}


working FIDDLE


Answer




It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):



ul $li ul.sub { ... }


See the list of CSS4 Selectors here.



As an alternative, with jQuery, a one-liner you could make use of would be this:



$('ul li:has(ul.sub)').addClass('has_sub');



You could then go ahead and style the li.has_sub in your CSS.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...