且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否有任何方法为“除第一/最后一个”之外的所有元素指定CSS速记?

更新时间:2023-11-03 09:51:16

对于所有 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.