【问题标题】:Direct children (Child combinator) selector not restricting to children直接子级(子级组合器)选择器不限于子级
【发布时间】:2021-07-17 00:29:55
【问题描述】:

为什么嵌套的<ol> 列表项会收到sqpurple.gif 项目符号?

ul > li {
  list-style: outside url("https://www.w3schools.com/cssref/sqpurple.gif") disc;
}
<ul>
  <li>&lt;ul&gt; - parent
    <ol>
      <li>&lt;ol&gt; - parent. Shouldn't this be a number?</li>
    </ol>
  </li>
</ul>
Windows 10 x64
Chrome v91.0.4472.114
Firefox v89.0.1
Edge v91.0.864.67

【问题讨论】:

  • 由于继承
  • @TemaniAfif 你能扩展一下吗?如果我没记错的话,ul &gt; li 应该将定位限制为仅限&lt;ul&gt;direct 子级。
  • 这和你在body { }里面写css几乎是一样的,css会全局传播给每个孩子。在您的情况下,我将其视为 ul &gt; li &gt; ol &gt; li,它仍在 ul &gt; li
  • 定位是一回事,继承是另一回事。如果仅将颜色设置为正文元素,则所有页面都将获得该颜色,因为颜色是继承属性。列表样式也一样
  • @TemaniAfif 请看我添加的例子。

标签: html css css-selectors html-lists


【解决方案1】:

https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image:

注意:此属性适用于列表项,即默认情况下具有display: list-item; 的元素包括&lt;li&gt; 元素。由于此属性是继承的,因此可以在父元素(通常为&lt;ol&gt;&lt;ul&gt;)上设置它以使其应用于所有列表项。

要解决此问题,您应该将 &lt;ol&gt; 重置为没有图像。

使用ul &gt; li 是有缺陷的,因为您应该在&lt;ul&gt;&lt;ol&gt; 上设置list-style-image 属性

ul {
  list-style-image: url("https://www.w3schools.com/cssref/sqpurple.gif");
}

ol {
  list-style-image: none;
}
<ul>
  <li>&lt;ul&gt; - parent
    <ol>
      <li>&lt;ol&gt; - parent. This is now a number as expected!
        <ul>
          <li>&lt;ul&gt; - parent</li>
        </ul>
      </li>
    </ol>
  </li>
</ul>

【讨论】:

    【解决方案2】:

    我也不得不解开这个谜题,而且我从事 CSS 已有 20 多年了。我认为最好的解释方法是 rule 是继承的,而不是选择器。也就是说,被选元素内的任何元素都会获得该规则,并且由于任何li 都接受list-style 属性规则,因此它适用。

    正如其他人所展示的,解决方案是覆盖内部列表项。您还可以实现 :not 伪选择器,以便在您的选择器中更具限制性。 (实际上,you can't,至少使用了组合器)。

    【讨论】:

      【解决方案3】:

      这是一个类似的帖子:https://stackoverflow.com/a/6367905/9730836

      您可以将样式重置为每个孩子(因为存在继承)。

      试试:

      ul>li {
        list-style: outside url("https://www.w3schools.com/cssref/sqpurple.gif") disc;
      }
      
      li * {
        list-style: initial;
      }
      <ul>
        <li>&lt;ul&gt; - parent
          <ol>
            <li>&lt;ol&gt; - parent. Shouldn't this be a number?</li>
          </ol>
        </li>
      </ul>

      【讨论】:

      • 这不符合预期
      猜你喜欢
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 2011-11-01
      • 2011-04-28
      • 2011-03-01
      • 1970-01-01
      • 2011-01-06
      • 2016-03-16
      相关资源
      最近更新 更多