MilkyTech
MilkyTech

Reputation: 1927

Conditionally style an element based on whether it contains a particular child element?

This is in reference to a nav menu on a site I am working on:
I have applied a hover style to these particular anchors (subnav buttons):

ul#css3menu ul li:hover>a {

Now I want to further style any of these anchors that have a child span element. How could I code that?
I have it somewhat working by applying the style to the span element:

ul#css3menu ul span:hover{

The problem with this is the style is only applied when hovering over the span element's space rather than while hovering over the anchor that is parent to the span (the entire subnav button including its padding)

Upvotes: 0

Views: 213

Answers (2)

MilkyTech
MilkyTech

Reputation: 1927

I just figured out a nifty solution without JS!!
The padding on the anchor is 8px and the padding on the span was set to 0 so I changed the padding on the span to 8 and set the margin to -8 and now the style works when hovering the entire button and I was still able to maintain the size of the button! Stoked!

ul#css3menu span{
display:block;
padding:8px;
margin:-8px 0 -8px -8px;
}

I had to leave the right margin alone to maintain the width of the button and the positioning of the next level subnav.

Upvotes: 0

Kjeld Schmidt
Kjeld Schmidt

Reputation: 768

CSS currently doesn't have a way to check for children (or, what would essentially be a 'parent selctor', something that often comes up as a wishful thought in discussions about css. Read more: http://css-tricks.com/parent-selectors-in-css/)

In order to style something like that, you'd have to use jQuery (or, javascript...)

$('ul').each(function () {
  if ($(this).find('span').length) {
    $(this).css({your style here});
  }
}

If what you do is not dynamic, it would always be easiest to give a class to those lists beforehand and style them.

Upvotes: 1

Related Questions