首页 > 解决方案 > 是否可以使特定 div 类中的最后一个 p 具有特定的 css?

问题描述

要使最后一个p没有边距,您可以这样做,但是一旦您开始嵌套在 otherlast-of-type中,这将不起作用。pdivs

p是否可以在指定的类中为最后一个具有特定的 css ?

例如:

<div class="my-container">
  <div class="banner-message1">
    <p>1</p>
  </div>
  <div class="banner-message2">
    <p>2</p>
  </div>
</div>

专门使它<p>2</p>具有一定的样式,但不是<p>1</p>

的 cssdiv.my-container p:last-of-type似乎适用于两者<p>1</p><p>2</p>因为它们是p父级中的最后一个div(在本例中banner-message1banner-message2

https://jsfiddle.net/hygzq3ab/

这是一个 jsfiddle,它在最后一个标签上有一个边距底部p,然后还有容器的填充,所以最后一个p元素看起来基本上就像它有一个双底边距。last-of-type似乎不起作用,因为它包含在其他 div 类中。

示例代码是div.my-container p:last-of-type { margin-bottom:0; }

标签: htmlcss

解决方案


如果<p>始终包含在 a 中,<div>那么您可以使用

.my-container > div:last-of-type p {
    margin-bottom: 0;
}

您需要定位最后一个 div 内的段落(在此特定示例中也可以:last-child代替)。:last-of-type


但是,如果您的最后一个<p>并不总是包含在 a 中,<div>那么您可以使用

.my-container > div:last-child p,
.my-container > p:last-child {
    margin-bottom: 0;
}

在这里你必须使用:last-child而不是:last-of-type或者——如果最后一个<p>没有被自己包裹<div>——你也将定位在最后一个包含的段落<div>


推荐阅读