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

spa*_*od_ 1 html css

为了让最后一个p没有边距,您可以这样做last-of-type,但是一旦您开始p嵌套在 other 中,这将不起作用divs

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

例如:

<div class="my-container">
  <div class="banner-message1">
    <p>1</p>
  </div>
  <div class="banner-message2">
    <p>2</p>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

专门使它<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标签上有一个 margin-bottom ,然后还有容器的 padding,所以最后一个p元素看起来基本上就像它有一个双底边距。last-of-type似乎不起作用,因为它包含在其他 div 类中。

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

fca*_*ran 6

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

.my-container > div:last-of-type p {
    margin-bottom: 0;
}
Run Code Online (Sandbox Code Playgroud)

你需要为目标的最后一个div内的第(也:last-child代替:last-of-type将在这个具体的例子以及工作)。


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

.my-container > div:last-child p,
.my-container > p:last-child {
    margin-bottom: 0;
}
Run Code Online (Sandbox Code Playgroud)

在这里,您必须使用:last-child代替:last-of-type或 - 如果最后一个<p>没有包装在它自己的范围内<div>- 您还将定位包含在最后一个中的段落<div>