css - How to target a selector only if it's NOT child of a specific element (so only if it's the root)

标签 css css-selectors

我不明白为什么以下代码没有预期的行为:

    .toggle {
      color: red;
    }
    
    :not(.list) .toggle {
      font-weight:bold;
    }
  <div class="container">
      <a href="#!" class="toggle">Toggle</a>
      <ul class="list">
        <li><a href="#!">Link 1</a></li>
        <li>
          <div class="container">
            <a href="#!" class="toggle">SubToggle</a>
            <ul class="list">
              <li><a href="#!">SubLink 1</a></li>
              <li>
                <a href="#!">SubLink 2</a>
              </li>
              <li><a href="#!">SubLink 3</a></li>
            </ul>
          </div>
        </li>
        <li><a href="#!">Link 3</a></li>
      </ul>
    </div>

我认为使用 :not() 会导致仅将“粗体”应用于主“切换”链接,但它会将“粗体”应用于所有红色链接。为什么?

请注意,这段代码嵌套了相同的类名,我不想用不同的 css 类来定位特定级别,我只想用后代选择器和其他运算符来定位元素

这里还有一个 jsFiddle直接试试。

最佳答案

我想你可能想要这个:

.toggle {
  color: red;
  font-weight: bold;
}

div *:not(.list) .toggle {
  font-weight: normal;
}

关于css - How to target a selector only if it's NOT child of a specific element (so only if it's the root),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40214442/

相关文章:

html - 如何通过 xlink :href attribute with CSS? 选择 XML 元素

css - 将鼠标悬停在 1 个 div 上时,让 2 个 div 改变颜色

html - 嵌套类的 CSS 选择器

css - div 不会在 bootstrap 中居中

html - 为什么这些几乎相同的页面的样式不同?

php - WooCommerce 结账字段未显示正确的错误消息

java - 可以在 ReSTLet Java SE 中使用 xml/css/json 吗?

html - 如何在 css3 选择器中交替显示两列的颜色?

css - 为任意深度的嵌套列表设置样式

html - 我如何养 child (位置:fixed) below the parent (`position:fixed` )?