Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

css - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...