【问题标题】:How do I hide the nth element starting from the back如何隐藏从后面开始的第 n 个元素
【发布时间】:2017-09-17 16:04:09
【问题描述】:

我试图从后面隐藏第 n 个 div 元素。 使用 :nth-last-child(n) 选择器只会隐藏 div 中的最后一个元素,而不是 div 本身。

我尝试了以下方法:

.block:nth-last-child(1) {display:none;}
以上没有做任何事情

.block :nth-last-child(1) {display:none;}
以上只隐藏了div中的第n个元素

.block:nth-last-child(1) {display:none;} 
<div class='block'>
    <button type="button">a</button>
    <button type="button">b</button>
    <button type="button">c</button>
</div>
<div class='block'>
    <button type="button">a</button>
    <button type="button">b</button>
    <button type="button">c</button>
</div>
<div class='block'>
    <button type="button">a</button>
    <button type="button">b</button>
    <button type="button">c</button>
</div>
<div class='block'>
    <button type="button">a</button>
    <button type="button">b</button>
    <button type="button">c</button>
</div>

【问题讨论】:

    标签: css


    【解决方案1】:
    .block:nth-last-child(2) {display:none;}
    

    【讨论】:

    • 这行得通,谢谢!我刚刚发现,如果要选择的元素之间还有其他元素(在我的示例中为 .block),则需要将这些元素添加到第 n 个的计数中。
    【解决方案2】:

    需要一个“父”元素才能有一个“子”

    .block:nth-last-child(2) {display:none;} 
    <div class='parent'>
    <div class='block'>
        <button type="button">a0</button>
        <button type="button">b0</button>
        <button type="button">c0</button>
    </div>
    <div class='block'>
        <button type="button">a1</button>
        <button type="button">b1</button>
        <button type="button">c1</button>
    </div>
    <div class='block'>
        <button type="button">a2</button>
        <button type="button">b2</button>
        <button type="button">c2</button>
    </div>
    <div class='block'>
        <button type="button">a3</button>
        <button type="button">b3</button>
        <button type="button">c3</button>
    </div>
    </div>

    【讨论】:

      【解决方案3】:

      您的选择器错误,您需要指定您要选择的按钮。

      类似的东西:

      .block button:last-child {display:none;}
      <div class='block'>
          <button type="button">1a</button>
          <button type="button">1b</button>
          <button type="button">1c</button>
      </div>
      <div class='block'>
          <button type="button">2a</button>
          <button type="button">2b</button>
          <button type="button">2c</button>
      </div>
      <div class='block'>
          <button type="button">3a</button>
          <button type="button">3b</button>
          <button type="button">3c</button>
      </div>
      <div class='block'>
          <button type="button">4a</button>
          <button type="button">4b</button>
          <button type="button">4c</button>
      </div>

      【讨论】:

      • 您好 Felix,如果我不清楚,我很抱歉。我的意思是我需要隐藏带有“block”类的整个 div(包括它的内容)