Friday 25 January 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...