html - CSS:在除最后一个以外的所有div上添加管道

标签 html css css-selectors

除了最后一个 .我的 html 以下列方式呈现,html 是用相同的类呈现的。

<!DOCTYPE html>
<html>
<head>
<style> 
p:last-of-type {
    background: #ff0000;
}
</style>
</head>
<body>

<h1>This is a heading</h1>
<div class="sample" style="display:inline-block">
    <div >
        <p class="para">link1</p>
    </div>
</div>
<div class="sample" style="display:inline-block">
    <div >
        <p class="para">link1</p>
    </div>
</div>
<div class="sample" style="display:inline-block">
    <div >
        <p class="para">link1</p>
    </div>
</div>


</body>
</html>

我需要添加管道,但在最后一个链接之后不应显示任何管道。对于这种情况,我该怎么做。

Fiddle Link

附言:当我们有不同类别的不同链接时,这可以很容易地完成。在我的例子中,链接是动态的,在最后一个链接之后不应显示任何管道

最佳答案

使用此选择器 .sample:not(:last-of-type),它将定位除最后一项以外的所有项。

请注意,当将类名与 last-of-type 组合时,它将针对任何不是最后一个(如果有超过 1 个)具有给定类的元素类型.

Updated fiddle (将管道添加到div,这样它就不会从p中获取颜色)

.sample:not(:last-of-type) > div::after {
  content: ' | ';
}

另一个选项是 last-child.sample:not(:last-child),它也将定位除最后一个之外的所有对象。

请注意,当使用 last-child 时,无论是类还是元素类型,它都表示最后一个,因此如果在最后一个 sample 之后有另一个元素>,这将算作最后一个,这里是 a fiddle sample显示在这种情况下此规则将如何失败。

Updated fiddle (将管道添加到div,这样它就不会从p中获取颜色)

.sample:not(:last-child) > div::after {
  content: ' | ';
}

第三种选择是使用直接兄弟元素选择器 +,它针对具有给定类的所有兄弟元素,但第一个。

p:last-of-type {
    background: #ff0000;
    display: inline-block;
}

.sample + .sample > div::before {
  content: ' | ';
}
<h1>This is a heading</h1>
<div class="sample" style="display:inline-block">
	<div >
		<p class="para">link1</p>
    </div>
</div>
<div class="sample" style="display:inline-block">
	<div >
		<p class="para">link1</p>
    </div>
</div>
<div class="sample" style="display:inline-block">
	<div >
		<p class="para">link1</p>
    </div>
</div>

关于html - CSS:在除最后一个以外的所有div上添加管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46400877/

相关文章:

css - 两种声明样式规则的方式之间的空间有什么区别

javascript - 添加一个类并删除当前类,以便 J Query 中的按钮可以重新用于不同的功能

javascript - jquery 可拖动,使 div 不超出另一个 div 框架

html - 如何将 HTML 表格单元格对齐为圆形

jquery - 如何让 Fancybox Next 和 Previous 按钮保持可见

css - 如何让 Internet Explorer 8 支持第 n 个 child() CSS 元素?

html - 防止 padding background-color 溢出到子元素中

css - 如何在html组合框中具有树状结构

javascript - 如何从元素中获取应用的样式,不包括默认的用户代理样式

css - 我可以使用 TinyMCE 格式配置为给定对齐的不同元素设置不同的类吗?