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

為{幸葍}努か 提交于 2020-01-16 19:16:56

问题


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)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/22898462/conditionally-style-an-element-based-on-whether-it-contains-a-particular-child-e

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!