是否有任何方法为“除第一/最后一个”之外的所有元素指定CSS速记? [英] Is there any way to specify a CSS shorthand for "all elements except the first/last"?

查看:163
本文介绍了是否有任何方法为“除第一/最后一个”之外的所有元素指定CSS速记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,自然需要为除第一个(或最后一个)元素之外的所有元素指定CSS样式。例如,在设计段落时,您希望为除最后一个元素以外的每个元素添加一个底部边距(或者类似地,除第一个元素之外的每个元素的顶部边距)。

Very often, it's natural to need to specify a CSS style for all elements except the first (or the last). For example, when styling paragraphs, you wish to add a bottom margin to every element except the last one (or similarly, a top margin to every element except the first one).

是否有任何方法:


  • 比定义 p {...} / code>,然后 p:first-child {...}

  • c $ c> p:nth-​​child(-n + 1)

  • more concise than defining p {...} and then p:first-child {...}?
  • more straightforward and intuitive than p:nth-child(-n+1)?

推荐答案

对于所有 p 元素,除了第一个孩子,使用其中的一个(第二个是更好的支持):

For all p elements except the first child, use either one of these (the second one is better-supported):

p:not(:first-child)
p:first-child ~ p

$ c> p 除最后一个子元素之外的元素:

For all p elements except the last child:

p:not(:last-child)

对于所有 p 元素最后的孩子:

For all p elements except the first and the last children:

p:not(:first-child):not(:last-child)

像往常一样,CSS3的:not():last-child 不支持,直到IE9 +和其他浏览器的相对新版本。除非您使用JavaScript或其他方式向第一个和最后一个孩子添加类,否则您不会在浏览器支持(IE8及更早版本)方面达到非常远。

As usual, CSS3's :not() and :last-child aren't supported until IE9+ and relatively new versions of other browsers. You're not going to reach very far in terms of browser support (IE8 and older) unless you add classes to your first and last children, using JavaScript or otherwise.

请记住,横向边距在流内段落及其祖先之间折叠,因此除非你想把这些段落的容器元素的边距清零,你不需要特别清空第一个和最后一个 p 元素的边距。这是一个小提琴来说明。

Remember that vertical margins collapse between in-flow paragraphs and their ancestor(s), so unless you want to zero out the margins of the container element for these paragraphs as well, you shouldn't need to zero out the margins of the first and last p elements specifically. Here's a fiddle to illustrate.

这篇关于是否有任何方法为“除第一/最后一个”之外的所有元素指定CSS速记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆