CSS :nth-of-type() 和 :not() 选择器?

问题描述 投票:0回答:3

我并排浮动了 25% 宽的文章。我在每四个元素后面添加一个

clear:both
。但是我需要在元素之间插入图形分节符。而且它必须在
<ul>
内部。为了有效,我也将“分节符”(下面示例中的第一个 li 项)包装到
<li>
中。

<ul>
    <li class="year"><h1>THIS IS A SECTION Break and 100% wide</h1></li>
    <li>This is a article and only 25% wide</li>
    <li>This is a article and only 25% wide</li>
    <li>This is a article and only 25% wide</li>
    <li>This is a article and only 25% wide</li>
</ul>

我希望每四个元素都是一个换行符,所以我使用......

ul li:nth-of-type(4n+1) { clear: both; }

但是我希望

li.year
不要受到这种行为的影响,所以我尝试了这个

ul li:not(.year):nth-of-type(4n+1) { clear: both; }

现在,上面示例代码中的最后一个

<li>
已浮动到下一行,但这不应该发生,因为第一个
<li>
不是浮动文章之一,而是包含标题。

是否可以将

:not
nth-of-type()
选择器堆叠在一起?

css css-float css-selectors
3个回答
10
投票

您的

:not()
似乎不起作用的原因是因为
li.year
与其余
li
元素具有相同的元素类型(自然地),因此无论
 如何,
:nth-of-type(4n+1)
 都会匹配相同的元素.year
上课。

也不可能按顺序堆叠选择器。这不是他们的工作方式。

由于 HTML 标记规则的原因,您无法将

li
元素更改为其他内容,并且
:nth-match()
位于 未来规范 中且尚未实现,因此您必须设法更改
:nth-of-type() 
适应结构的公式:

ul li:not(.year):nth-of-type(4n+2) { clear: both; }

9
投票

您拥有的选择器 --

ul li:not(.year):nth-of-type(4n+1) { background: yellow; }

-- 完全正确(如突出显示选择器所示)。

问题在于您如何使用

clear
。如果您使用
clear:right
,然后在以下元素上使用
clear:left
,则可以使用:

ul li:not(.year):nth-of-type(4n+1) { clear: right;  }
ul li:not(.year):nth-of-type(4n+2) { clear: left;  }

按评论编辑删除的文字是无稽之谈。根据 BoltClock 的回答,真正的问题是

:not
伪类不会影响
nth-of-type
。在这种情况下,调整选择器偏移量是巧合,但如果
:not
模式不同,则不起作用。

ul li:not(.year):nth-of-type(4n+2) { clear: left;  }

http://jsfiddle.net/8MuCU/


0
投票

为了更新这一点,这里有一篇:

ul li:nth-child(4n+1 of :not(.year)) {
  clear: both;
}

我们可以使用 nth-child 代替 nth-of-type ,据我所知,现在所有常见的浏览器在使用“of”参数时都支持 nth-child() 内部的 :not() 。

© www.soinside.com 2019 - 2024. All rights reserved.