首页 > 解决方案 > 包裹在其他父母中的元素的最后一个孩子?

问题描述

我试过hr:last-child了,但没有用。这是我的 HTML 结构:

    <div>
      <hr />
    </div>
    <div>
      <hr />
      // hide this
    </div>

只有当我有 hr 作为兄弟姐妹时,它才有效。

标签: htmlcss

解决方案


虽然您可以通过定位父 div 并使用直接兄弟组合器来定位它,然后在其中添加类或更好的 hr 会更好 - 更改 html。此外,我建议使用 csss 添加诸如边框底部之类的内容,而不是 hr html 元素。

但是这里有 - 定位兄弟的 div - 然后在不是第一个兄弟的 div 中 - 定位 hr 并使用 display:none 隐藏它。仍然不是我会这样做的方式。

我在 div 中添加了文本和填充,以证明在第二个选项中删除了 hr。

编辑 - 实际上 - 只是想到了一种更简单的方法....但前提是你想将它们隐藏在不是第一个的所有 div 中。

.hide-hr div:not(:first-child) hr{display:none};

div {
padding: 5px
}

p {
margin: 0;
}

 div + div {
  border-top-width:0;
 }


.hide-hr {
  margin-top: 15px;
}

.hide-hr div + div hr {
  display: none;
 }
<p> the following shows the hr in the second div</p>

<div class="show-hr">
  <div>
    <p>div 1</p>
    <hr/>
  </div>
  <div>
    <p>div 2</p>
    <hr/>
  </div>
</div>


<p> the following hides the hr in the second div</p>
<div class="hide-hr">
  <div>
    <p>div 1</p>
    <hr/>
  </div>
  <div>
    <p>div 2</p>
    <hr/>
  </div>
</div>


推荐阅读