问题
我想将样式应用于NOT 特定类型的元素的最后一个子元素。
请不要混淆:最后一个元素IF它不是某种类型。
例子
<div class="container>
<div>Child 1</div>
<div>Child 2</div>
<span>Child 3</span>
<template></template>
<span>Child 4</span>
<template></template>
</div>
在这种情况下,我想将样式应用到最后一个不是 <template>
类型的元素(在这种情况下将是 Child 4)。
请注意:nth-last-child(2)
不适用,因为可能有更多 <template>
元素。
我尝试过的(但没有奏效)
.container > :not(template):last-child {
// Style here
}
.container > :last-child:not(template) {
// Style here
}
已经谢谢你了!
编辑 - 看来我的问题是抽象的,所以我会更具体。
我想要一个通用的间距类(将其应用于容器只会在元素之间添加一个空格):
.vertical-spacing>* {
margin: 20px 0;
}
.vertical-spacing> :first-child {
margin-top: 0;
}
.vertical-spacing> :last-child {
margin-bottom: 0;
}
/* For better visibility of example */
.vertical-spacing {
background: #ff0000
}
.vertical-spacing>* {
background: #00ff00;
}
<div class="vertical-spacing">
<div>Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
</div>
我正在 Polymer 3.0 中做一个元素,您可以在其中使用仅在特定条件下可见的条件模板:
<template is="dom-if" if="condition">
<div>Content</div>
</template>
如果<template>
是间距容器中的最后一个 child (或者多个模板都是最后一个 child ,数量不固定)且条件为false,结果为<template>
的内容是隐藏的,但是 <template>
元素本身仍然存在。结果在容器的末尾有一个无用的空间:
.vertical-spacing>* {
margin: 20px 0;
}
.vertical-spacing> :first-child {
margin-top: 0;
}
.vertical-spacing> :last-child {
margin-bottom: 0;
}
/* For better visibility of example */
.vertical-spacing {
background: #ff0000
}
.vertical-spacing>div {
background: #00ff00;
}
<div class="vertical-spacing">
<div>Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
<temlate>
<div style="display: none">Content</div>
</temlate>
</div>
<div style="background: #0000ff; color: white">Stuff after container: there is a margin on top as you can see</div>
我现在希望能够将移除边距的样式应用于容器中最后一个不是 <template>
的元素。 .
最佳答案
.vertical-spacing>* {
margin: 20px 0;
}
.vertical-spacing> :first-child {
margin-top: 0;
}
.vertical-spacing> :last-child {
margin-bottom: 0;
}
/* For better visibility of example */
.vertical-spacing {
background: #ff0000
}
.vertical-spacing>* {
background: #00ff00;
}
.vertical-spacing > *:last-of-type {
margin-bottom:0;
}
span{
display:inline-block;
}
<div class="vertical-spacing">
<div>Child 1</div>
<div>Child 2</div>
<div>Child 3</div>
<p>'p' tag child </p>
<span>'span' tag child </span>
<div>Child 3</div>
<span>'span' tag child </span>
<template>
<div style="display: none">Content</div>
</template>
</div>
<div style="background: #0000ff; color: white">Stuff after container: there is a margin on top as you can see</div>
简单写
.vertical-spacing > *:last-of-type { margin-bottom:0;}
我认为这将解决您的 margin 问题。
关于CSS - 将样式应用于不属于特定类型的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56474011/