定义紧邻另一个元素 CSS 之前和之后的元素的样式
在过去的一个小时里,我一直在寻找正确的 CSS 选择器(或者至少找出是否存在)来为 DOM 中另一个元素之前和之后的元素设置样式。
目前,我有一个 ul
,其 li
元素具有 border-bottom
属性。如果 DOM 中紧随其后的元素有一个元素,我想更改该边框的颜色。如果可能的话,我想避免为此使用单独的类。
考虑以下标记:
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li class="divider">2</li>
<li>List Item 4</li>
<li>etc.</li>
</ul>
我想将 border-bottom: none
添加到
List Item 3
和任何其他 li 元素紧跟在 li.divider
后面。
是否有一个 CSS 选择器,例如 ul > li
,但是为了这个?不需要跨浏览器,可以是CSS3;只需要在 WebKit 浏览器上工作...
I have been searching for the past hour to find the correct CSS Selector (or at least to find out if one exists) to style the elements in the DOM immediately before and after another element.
At the moment, I have a ul
whose li
elements have a border-bottom
property. I would like to change the colour of that border if there is an element immediately after it in the DOM. If possible, I would like to avoid using separate classes for this.
Consider the following markup:
<ul>
<li>List Item 1</li>
<li>List Item 2</li>
<li>List Item 3</li>
<li class="divider">2</li>
<li>List Item 4</li>
<li>etc.</li>
</ul>
I would like to add border-bottom: none
to <li>List Item 3</li>
and any other li
elements that are immediately followed by li.divider
.
Is there are a CSS selector for this, something like ul > li
, but for this? It doesn't need to be cross-browser, and can be CSS3; just needs to work on WebKit browsers...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是不可能的。前面的元素没有 css 选择器;既不是先前的兄弟姐妹,也不是祖先。
但是,您可以将样式应用于下一个(并且仅下一个)同级:
您可以将其链接起来。这种风格:
和这个(可组合):
允许您仅应用“predivider”类或“divider”类中的一个,具体取决于分隔符是否是第一个元素(因此前面没有元素)。
this is not possible. there is no css selector for preceding elements; neither preceding siblings, nor ancestors.
you can, however, apply a style to the next (and only the next) sibling:
you can chain it. this style:
and this (combinable):
allows you to apply just one of either the “predivider” class, or the “divider” class, dependent of the divider being the first element (and thus has none before it) or not.
.divider + li
选择将同级直接映射到
.divider
。至于前面的,我认为不可能(如有错误,请指正)
.divider + li
to select to immidiate sibling<li>
to.divider
.As for the one before it, I don't think it's possible (please correct me if I'm wrong)