【问题标题】:Count children in parent via CSS [duplicate]通过CSS计算父母中的孩子[重复]
【发布时间】:2016-08-24 10:03:04
【问题描述】:

如何计算<ul> 中的儿童<li>

如果<ul> 在一个<ul> 中小于或等于6 个<li>,我想隐藏最后一个<li>

代码

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span></li>
</ul>

Fiddle

【问题讨论】:

  • 你不能计算 CSS 中的元素。您必须使用 javascript 进行计算,然后您可以添加或删除类名来实现您想要的
  • css中有一个方法。我知道这很棘手。但我们可以做到。
  • 是什么让你如此确定?
  • 题名很混乱
  • @BoltClock :不能将此问题标记为与您选择的问题重复,因为这两个查询的解决方案不同。 li:nth-of-type(5) + li, :nth-child(-n+5).more { display: none; }

标签: css css-selectors pseudo-class


【解决方案1】:

您可以使用nth-of-type()(或nth-child())加上相邻的选择器+

li {
  background: red
}
.more {
  background: green
}
li:nth-of-type(5) + li {
  display: none
}
<h1> 6 items </h1>

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
</ul>

<h1> 5 items </h1>


<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
</ul>

<h1> 7 items </h1>

<ul>
  <li>one</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Five</li>
  <li class="more"><span>Hide this if only 6 li's are there in this ul</span>
  </li>
  <li>Seven</li>
</ul>

【讨论】:

  • 这将隐藏第 6 个列表项,即使列表中的列表项超过 6 个
  • @fcalderan 但 OP 说它不再有 6 个元素:如果
      只有 6 个
    • 在一个
        中,我想隐藏最后一个
      • .
  • 这实际上解决了我在查询中写的任何内容,但还有一个条件是......如果&lt;li&gt; 计数小于或等于 6,我需要隐藏它。
  • 这与您的原始问题不同。
  • @Marcos Pérez Gude:她最初的问题是“只有 6 个”,现在她说“还有一个条件是......如果
  • 计数小于或等于6.”
【解决方案2】:

如果您需要隐藏.more 元素当且仅当(正如我从问题中理解的那样)您的列表有 6 个列表项,那么您可以这样做

li:nth-last-child(6):first-child ~ .more {
  display: none;
}

如果从最后一个元素算起,nth-last-child(6) 元素也是第一个子元素,那么列表必须正好有 6 个列表项。


Codepen example

从示例中可以看出,在第一个列表中,第 6 个 元素不受影响,因为列表不仅有 6 个列表项

【讨论】:

    【解决方案3】:

    使用以下代码来实现:

    li:nth-of-type(6):last-child {
      display:none;
    }
    <h3>Remove nothing</h3>
    <ul>
      <li>Test #1</li>
      <li>Test #2</li>
      <li>Test #3</li>
      <li>Test #4</li>
      <li>Test #5</li>
      <li>Test #6</li>
      <li>Test #7</li>
    </ul>
    <h3>Remove #6</h3>
    <ul>
      <li>Test #1</li>
      <li>Test #2</li>
      <li>Test #3</li>
      <li>Test #4</li>
      <li>Test #5</li>
      <li>Test #6 (hide this)</li>
    </ul>
    <h3>Remove nothing</h3>
    <ul>
      <li>Test #1</li>
      <li>Test #2</li>
      <li>Test #3</li>
      <li>Test #4</li>
      <li>Test #5</li>
    </ul>

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签