是否可以使特定 div 类中的最后一个 p 具有特定的 css?



要使最后一个p没有边距,您可以执行last-of-type,但是一旦您开始将p嵌套在其他divs中,这就不起作用了。

是否可以为指定类中的最后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>

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

https://jsfiddle.net/hygzq3ab/

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

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

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

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

您需要定位最后一个div 中的段落(也是:last-child而不是:last-of-type在这个特定示例中也可以(。


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

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

在这里,您必须使用:last-child而不是:last-of-type或者 - 如果最后一个<p>没有包装在其自己的<div>中 - 您还将定位最后一个<div>中包含的段落

这是你要的吗?

html(你的小提琴确实有很多相同的元素的ID(

<div class="my-container">
<div class="banner-message">
<p>
1
</p>
</div>
<div class="banner-message">
<p>
2a
</p><p>
2b
</p>
</div>
<div class="banner-message">
<p>
aaa
</p>
</p>
<p>
3
</p>
</div>
</div>

和 css:

.banner-message:last-child p:last-child {
color: red
}

应该做这个技巧

> 你也应该使用它:last:child

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

最新更新