【问题标题】:Add padding to all childs except last为除最后一个之外的所有孩子添加填充
【发布时间】:2014-11-09 14:01:27
【问题描述】:

我正在尝试将padding 添加到div 的所有子元素中,除了最后一个。

我尝试对last-child 使用否定,但当我使用它时,它甚至没有将padding 添加到其余子元素中......

这是我的 HTML:

#container .description:not(:last-child) {
  padding-bottom: 10px;
}
<div id="container">
  <h3>Title</h3>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 1</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  Testing here
</div>

JSFiddle Demo

【问题讨论】:

  • 所有.description元素都是他们父母的:last-child;因此您的选择器不选择任何元素,因此不应用任何样式。
  • 如果您愿意更改您的标记:codepen.io/anon/pen/AEhFb

标签: html css css-selectors pseudo-class


【解决方案1】:

以下规则应该是您正在寻找的。除了最后一个 .box 元素中的描述之外,它将为所有描述添加 10px 的填充:

#container .box:not(:last-child) .description{
    padding-bottom:10px;
}

Example fiddle

【讨论】:

  • 有什么方法可以使用否定吗?有点像我试过的?
  • @imbondbaby 将答案改为使用否定,但否定不是必需的(除非你真的只想要一个规则)
  • 非常感谢!那行得通,我也看到了!当我可以的时候会接受答案
  • 最干净的解决方案 - 除非 IE7/8 是严格要求。 E7 and IE8 support only these CSS3 selectors: General siblings (element1~element2) and Attribute selectors [attr^=val], [attr$=val], and [attr*=val] - CanIUse
【解决方案2】:

你大概想要:

#container .description {
    padding-bottom: 10px;
}

#container > :last-child .description {
    padding-bottom: 0;
}

正如您当前编写的选择器:

#container .description:not(:last-child){
    padding-bottom:10px;
}

它无法匹配任何元素,因为所有 .description 元素都是其父元素的最后一个子元素。

针对 cme​​ts,一种使用否定运算符的不必要的复杂(和有限的跨浏览器兼容)方法:

#container .box:not(:last-child) .description {
    padding-bottom: 10px;
}

【讨论】:

  • 有什么方法可以使用否定吗?有点像我试过的?
  • 为什么要不必要地使用否定运算符?我的意思是:是的,当然有,但是为什么?
【解决方案3】:

改用:last-child怎么样,很简单,不需要使用否定选择器:not(支持比:first/last-child少)。

#container .box:last-child{
  padding-bottom: 0;
}

sn-p

#container {
  border: 1px solid
}

#container .box {
  padding-bottom: 10px
}

#container .box:last-child {
  padding-bottom: 0;
}
<div id="container">
  <h3>Title</h3>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 1</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  Testing here
</div>

【讨论】:

    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 2011-11-08
    • 2013-03-19
    相关资源
    最近更新 更多