首页 > 解决方案 > CSS - 将样式应用于不是特定类型的最后一个元素

问题描述

问题

我想将样式应用于不是某种类型的元素的最后一个子元素。

请不要混淆:最后一个元素如果它不是某种类型。

例子

<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>是间隔容器中的最后一个子元素(或多个模板是最后一个子元素,数量不固定)并且条件为假,则结果是<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>.

标签: csspolymer-3.x

解决方案


.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;}

我认为这将解决您的保证金问题。


推荐阅读