给父元素中除了第一个子元素外其他子元素设置上外边距,用CSS实现为什么不能这样写?

HTML

<div class="container">
<div class="row"></div>
<div class="row"></div>
<div class="row"></div>
</div>

css

.container { width: 500px; height: 500px;}
.row { height: 1.5em; width: 100%; background-color: pink;}

正确的实现方式 
.row:not(:nth-child(1)) { margin-top: 10px; }

 错误的实现方式
.row:not(.row:nth-child(1)) { margin-top: 10px; }
.row:not(.row:first-child) { margin-top: 10px; }

正确的效果:

image.png

我不太明白为什么这两种错误的方式错在哪里?

阅读 3.2k
2 个回答

我查了下文档,大概总结下是因为 :not() 伪类选择器只能接收一个简单选择器作为参数。
而你的例子中后两个 :not() 中传入的都不是一个简单选择器,而是一个简单选择器序列,所以是不生效的。
这是我根据文档的理解,下面是文档中的相关引用。

简单选择器和简单选择器序列

A simple selector is either a type selector, universal selector, attribute selector, class selector, ID selector, or pseudo-class.
一个简单选择器可以是类型选择器,通用选择器,属性选择器,类选择器,ID选择器或伪类选择器。

A sequence of simple selectorsis a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.
一个简单选择器序列是一条不用组合器分隔的简单选择器链。通常是以类型选择器或通用选择器开头。序列中不允许出现其他类型选择器或通用选择器。

:not() 选择器

The negation pseudo-class,:not(X), is a functional notation taking a simple selector(excluding the negation pseudo-class itself) as an argument. It represents an element that is not represented by its argument.

前往文档

这个...一般使用兄弟选择器就可以:

.row + .row {
  margin-top: 10px;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题