CSS 仅在第一级的子元素上应用样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10282604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 03:41:24  来源:igfitidea点击:

Apply style only on child elements in the first level

css

提问by Alex

<ul>
  <li> <span> apply </span> </li>
  <li> <span> apply </span> </li>
  <li> 
    <ul>
      <li> <span> ignore </span> </li>
      <li> <span> ignore </span> </li>
    </ul>
  </li>
</ul>

How can I apply a CSS rule only to span elements from the first level, and make span elements from the nested list ignore the rule?

如何仅将 CSS 规则应用于第一级的 span 元素,并使嵌套列表中的 span 元素忽略该规则?

Can this be done without specifically resetting the properties on the 2nd level spans?

这可以在不专门重置第二级跨度的属性的情况下完成吗?

Tried ul > li spanbut it doesn't seem to work, I get the styles applied to 2nd level too

尝试过ul > li span但似乎不起作用,我也将样式应用于第二级

回答by sp00m

Put your list in a wrapping div with an ID, for example <div id="ul-wrapper">, and try:

将您的列表放在一个带有 ID 的包装 div 中,例如<div id="ul-wrapper">,并尝试:

#ul-wrapper > ul > li > span {
    /* my specific CSS */
}

回答by James Allardice

As long as the parent of the outer ulisn't another li, you can use that as the starting point for your selector (example assuming it's a div):

只要外部的父级ul不是 another li,您就可以将其用作选择器的起点(例如假设它是 a div):

div > ul > li span {
    /* Whatever */
}

回答by aghoshx

 #container >  ul > li span { /* - Your CSS Here - */  }

Need to specify a container, so that only the first level ul may be selected.

需要指定一个容器,这样只能选择第一级ul。

回答by rt2800

ul > li > span {border:solid 1px red;}
li > ul > li > span {border:none 1px red;};