是否有“以前的兄弟姐妹”?选择器?
加号选择器 (+
) 用于选择下一个相邻的同级。
前一个兄弟姐妹有同等的吗?
The plus sign selector (+
) is for selecting the next adjacent sibling.
Is there an equivalent for the previous sibling?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
- 考虑 Flex 和网格布局的 order 属性。
- jsFiddle
- 旁注 – 关于 CSS
- Consider the order property of flex and grid layouts.
- jsFiddle
- A Side Note – Two Outdated Beliefs about CSS
- 1. 使用 CSS Flex 和 row-reverse
- 2.使用带有方向的Flex:RTL
- 3.使用右浮动
- 1. Using CSS Flex and row-reverse
- 2. Using Flex with direction: RTL
- 3. Using float right
- 您可以使用两个axe选择器:!和?
- You can use the two axe selectors: ! and ?
- 另一种 Flexbox 解决方案
- Another flexbox solution
- 限制
- Limitations
发布评论
评论(30)
不,没有“前一个兄弟”选择器。
与此相关的是,
~
用于一般后继同级元素(意味着该元素位于该元素之后,但不一定紧随其后),并且是一个 CSS3 选择器。+
代表下一个同级,是 CSS2.1。请参阅 选择器级别 3 和 5.7 相邻同级选择器 来自 级联样式表 2 级修订 1 (CSS 2.1) 规范。
No, there is no "previous sibling" selector.
On a related note,
~
is for general successor sibling (meaning the element comes after this one, but not necessarily immediately after) and is a CSS3 selector.+
is for next sibling and is CSS2.1.See Adjacent sibling combinator from Selectors Level 3 and 5.7 Adjacent sibling selectors from Cascading Style Sheets Level 2 Revision 1 (CSS 2.1) Specification.
4 级选择器建议
:has()
允许您通过以下方式选择前一个同级:或(对于一般的前一个同级而不是相邻的):
它具有出色的 浏览器支持。
Selectors level 4 proposes
:has()
which allows you to select a previous sibling with:or (for a general previous sibling rather than adjacent one):
It has excellent browser support.
我找到了一种对所有以前的兄弟姐妹进行样式设置的方法(与
~
相反),该方法可能会根据您的需要而起作用。假设您有一个链接列表,当鼠标悬停在其中一个链接上时,所有之前的链接都应该变成红色。你可以这样做:
I found a way to style all previous siblings (opposite of
~
) that may work depending on what you need.Let's say you have a list of links and when hovering on one, all the previous ones should turn red. You can do it like this:
考虑 Flex 和网格布局的
order
属性。我将在下面的示例中重点关注 Flexbox,但相同的概念也适用于 Grid。
使用 Flexbox,可以模拟以前的同级选择器。
特别是,flex < code>order 属性可以在屏幕上移动元素。
这是一个例子:
步骤
将
ul
设为 Flex 容器。反转标记中同级的顺序。
<前><代码>
;- B
- A
使用同级选择器来定位元素 A(
~
或+
就可以了)。使用 flex
order
属性可恢复视觉显示上同级的顺序。...瞧!前一个同级选择器诞生了(或者至少是模拟的)。
这是完整的代码:
来自弹性盒规范:
所有 Flex 项目的初始
order
值为 0。另请参阅
顺序
。使用 flex
order
属性创建的“前一个同级选择器”示例。jsFiddle
旁注 – 关于 CSS
Flexbox 的两个过时的信念正在粉碎人们长期以来的信念关于CSS。
其中一个信念是CSS 中不可能存在前一个同级选择器。
说这种信念很普遍是轻描淡写的。以下是 Stack Overflow 上的相关问题示例:
如上所述,这种信念并不完全正确。可以使用 flex
order
属性在 CSS 中模拟先前的同级选择器。z-index
神话另一个长期存在的信念是
z-index
仅适用于定位元素。事实上,该规范的最新版本 - W3C 编辑草案 – 仍然断言这是真的:
然而,实际上,这些信息已经过时且不准确。
弹性项目 或 网格项position 为
static
,strong> 也可以创建堆叠上下文。以下是
z-index
在非定位弹性项目上工作的演示:https://jsfiddle。净/m0wddwxs/Consider the
order
property of flex and grid layouts.I'll focus on flexbox in the examples below, but the same concepts apply to Grid.
With flexbox, a previous sibling selector can be simulated.
In particular, the flex
order
property can move elements around the screen.Here's an example:
STEPS
Make the
ul
a flex container.Reverse the order of siblings in the mark-up.
Use a sibling selector to target Element A (
~
or+
will do) .Use the flex
order
property to restore the order of siblings on the visual display....and voilà! A previous sibling selector is born (or at least simulated).
Here's the full code:
From the flexbox spec:
The initial
order
value for all flex items is 0.Also see
order
in the CSS Grid Layout spec.Examples of "previous sibling selectors" created with the flex
order
property.jsFiddle
A Side Note – Two Outdated Beliefs about CSS
Flexbox is shattering long-held beliefs about CSS.
One such belief is that a previous sibling selector is not possible in CSS.
To say this belief is widespread would be an understatement. Here's a sampling of related questions on Stack Overflow alone:
As described above, this belief is not entirely true. A previous sibling selector can be simulated in CSS using the flex
order
property.The
z-index
MythAnother long-standing belief has been that
z-index
works only on positioned elements.In fact, the most current version of the spec – the W3C Editor's Draft – still asserts this to be true:
In reality, however, this information is obsolete and inaccurate.
Elements that are flex items or grid items can create stacking contexts even when
position
isstatic
.Here's a demonstration of
z-index
working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/我也有同样的问题,但后来我有一个“呃”时刻。而不是写
write
显然这匹配“x”而不是“y”,但它回答了“是否有匹配?”问题,简单的 DOM 遍历可能比在 javascript 中循环更有效地让你找到正确的元素。
我意识到原来的问题是一个 CSS 问题,所以这个答案可能完全无关,但其他 Javascript 用户可能会像我一样通过搜索偶然发现这个问题。
I had the same question, but then I had a "duh" moment. Instead of writing
write
Obviously this matches "x" instead of "y", but it answers the "is there a match?" question, and simple DOM traversal may get you to the right element more efficiently than looping in javascript.
I realize that the original question was a CSS question so this answer is probably completely irrelevant, but other Javascript users may stumble on the question via search like I did.
没有“前一个选择器”,但您可以使用
:not
和~
(“后选择器”)的组合。没有相反的顺序,没有 JavaScript。我认为我的方法比“设置所有 div 的样式,而不是删除 div 之后的样式”,或者使用 javascript,或者使用相反的顺序更直接。
There's not "previous selector", but you can use the combination of
:not
and~
("after selector"). No reverse order, no javascript.I think my approach is more straight-forward than "style all divs, than remove styling for after divs", or using javascript, or using reverse order.
三个技巧:
基本上,反转 HTML 中元素的 HTML 顺序,
并使用
~
Next brothers 运算符:1. 使用 CSS Flex 和 row-reverse
2.使用带有方向的Flex:RTL
3.使用右浮动
Three tricks:
basically, reversing the HTML order of your elements in HTML,
and using the
~
Next siblings operator:1. Using CSS Flex and row-reverse
2. Using Flex with direction: RTL
3. Using float right
您可以使用两个axe选择器:
!
和?
有2< em> 传统 CSS 中的后续同级选择器:
+
是直接 后续同级选择器~
是任意 后续同级选择器在传统的 CSS 中,没有上一个同级选择器。
但是,在 axe CSS 后处理器库中,有 2 个先前的同级选择器:
?
是直接上一个同级选择器(与+
相反)!
是任何上一个同级选择器(与~
相反)工作示例:
在下面的示例中:
.any-subsequent:hover ~ div
选择任何后续div< /code>
.immediate-subsequent:hover + div
选择紧随其后的div
.any-previous:hover ! div
选择任何先前的div
.immediate-previous:hover ? div
选择前一个div
You can use the two axe selectors:
!
and?
There are 2 subsequent sibling selectors in conventional CSS:
+
is the immediate subsequent sibling selector~
is the any subsequent sibling selectorIn conventional CSS, there is no previous sibling selector.
However, in the axe CSS post-processor library, there are 2 previous sibling selectors:
?
is the immediate previous sibling selector (opposite of+
)!
is the any previous sibling selector (opposite of~
)Working Example:
In the example below:
.any-subsequent:hover ~ div
selects any subsequentdiv
.immediate-subsequent:hover + div
selects the immediate subsequentdiv
.any-previous:hover ! div
selects any previousdiv
.immediate-previous:hover ? div
selects the immediate previousdiv
2023 年情况发生了变化。现在有了这样的选择器:
如果你想选择之前的 3 个项目,你可以这样做:
在此处查看我的演示 https://codepen.io/ro31337/pen/YzJbEZv
Things have changed in 2023. Now there is such selector:
If you want to select 3 items before, you do something like:
See my demo here https://codepen.io/ro31337/pen/YzJbEZv
另一种 Flexbox 解决方案
您可以使用 HTML 中元素的相反顺序。然后,除了使用Michael_B的答案中的
order
之外,您还可以使用flex-direction: row -reverse;
或flex-direction: column-reverse;
取决于您的布局。工作样本:
Another flexbox solution
You can use inverse the order of elements in HTML. Then besides using
order
as in Michael_B's answer you can useflex-direction: row-reverse;
orflex-direction: column-reverse;
depending on your layout.Working sample:
目前还没有官方方法可以做到这一点,但您可以使用一些小技巧来实现这一点!请记住,它是实验性的,并且有一些限制......
(如果您担心导航器兼容性,请检查此链接)
您可以做的是使用CSS3选择器:伪类称为
nth-child()
限制
There is no official way to do that at the moment but you can use a little trick to achieve this ! Remember that it is experimental and it has some limitation ...
(check this link if you worries about navigator compatibility )
What you can do is use a CSS3 selector : the pseudo classe called
nth-child()
Limitations
您可以使用双重否定
将
SELECTOR
替换为TAG
或.CLASS
(使用#ID
可能过于具体)。将
FILTER
替换为其他:PSUEDO-SELECTOR
(我只尝试过:hover
)或.CLASS
(更多关于通过 Javascript 进行切换的信息)。由于典型用法可能依赖于悬停(请参阅下面的示例)
You could use double negation
Replace
SELECTOR
with either theTAG
or.CLASS
( Using#ID
is probably too specific ).Replace
FILTER
with some other:PSUEDO-SELECTOR
(I've only tried:hover
) or.CLASS
(More for toggling through Javascript).Since the typical usage will probably rely upon hovering (See example that follows)
我的要求是在 @Quentin 的答案的帮助下选择当前悬停项目的前一个和后两个兄弟姐妹,我选择了前一个兄弟姐妹。
选择所有先前的兄弟姐妹
My requirement was to select currently hovered item's previous and next two siblings with the help of @Quentin 's answer I selected previous siblings.
To select all previous siblings
覆盖悬停时下一个兄弟姐妹的样式,以便看起来只有前一个兄弟姐妹在悬停时添加了样式。
Overriding the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.
如果您知道确切的位置,则可以基于
:nth-child()
排除所有后续同级。这将选择第三个之前的所有
li
(例如第一个和第二个)。但是,在我看来,这看起来很难看,而且用例非常紧张。您还可以从右到左选择第 n 个子级:
其作用相同。
If you know the exact position an
:nth-child()
-based exclusion of all following siblings would work.Which would select all
li
s before the 3rd (e.g. 1st and 2nd). But, in my opinion this looks ugly and has a very tight usecase.You also could select the nth-child right-to-left:
Which does the same.
不可以。通过 CSS 是不可能的。它牢记“级联”;-)。
但是,如果您能够将 JavaScript 添加到您的页面,那么一点 jQuery 就可以帮助您实现最终目标。
您可以使用 jQuery 的
find
对目标元素/类/id 执行“向前查找”,然后回溯以选择您的目标。然后,您使用 jQuery 为您的元素重写 DOM (CSS)。
基于迈克·布兰特的回答,
下面的 jQuery 片段可能会有所帮助。
首先选择紧随
之后的所有
。
然后它“回溯”以从该组
中选择所有先前的
。
实际上,“前一个兄弟”已通过 jQuery 选择。
现在,使用
.css
函数传入该元素的 CSS 新值。就我而言,我正在寻找一种方法来选择 id 为
#full-width
的 DIV,但前提是它具有类为.companies< 的(间接)后代 DIV。 /代码>。
我可以控制
.companies
下的所有 HTML,但无法更改其上方的任何 HTML。并且级联只有一个方向:向下。
因此我可以选择所有
#full-width
。或者我可以选择仅跟随
#full-width
的.companies
。但我不能仅选择
#full-width
继续.companies
。而且,我再次无法在 HTML 中添加
.companies
任何更高的位置。 HTML 的那部分是在外部编写的,并包装了我们的代码。但使用 jQuery,我可以选择所需的
#full-width
,然后分配适当的样式:这会找到所有
#full-width .companies
,并仅选择那些.companies
,类似于如何使用选择器来定位 CSS 标准中的特定元素。然后它使用
.parents
进行“回溯”并选择.companies
的所有父级,但过滤这些结果以仅保留
#fill-width
元素,因此最终,如果它具有
.companies
类后代,它只会选择#full-width
元素。最后,它为结果元素分配一个新的 CSS (
width
) 值。jQuery 参考文档:
$() 或 jQuery():DOM 元素。
.find:获取当前匹配集合中每个元素的后代元素,由选择器、jQuery 对象或元素过滤。
.parents:获取集合中每个元素的前一个同级元素匹配的元素。如果提供了选择器,则仅当它与该选择器匹配时才会检索前一个同级(过滤结果以仅包含列出的元素/选择器)。
.css:为一组设置一个或多个 CSS 属性匹配的元素。
No. It is not possible via CSS. It takes the "Cascade" to heart ;-).
However, if you are able to add JavaScript to your page, a little bit of jQuery could get you to your end goal.
You can use jQuery's
find
to perform a "look-ahead" on your target element/class/id, then backtrack to select your target.Then you use jQuery to re-write the DOM (CSS) for your element.
Based on this answer by Mike Brant,
the following jQuery snippet could help.
This first selects all
<ul>
s that immediately follow a<p>
.Then it "backtracks" to select all the previous
<p>
s from that set of<ul>
s.Effectively, "previous sibling" has been selected via jQuery.
Now, use the
.css
function to pass in your CSS new values for that element.In my case I was looking to find a way to select a DIV with the id
#full-width
, but ONLY if it had a (indirect) descendant DIV with the class of.companies
.I had control of all the HTML under
.companies
, but could not alter any of the HTML above it.And the cascade goes only 1 direction: down.
Thus I could select ALL
#full-width
s.Or I could select
.companies
that only followed a#full-width
.But I could not select only
#full-width
s that proceeded.companies
.And, again, I was unable to add
.companies
any higher up in the HTML. That part of the HTML was written externally, and wrapped our code.But with jQuery, I can select the required
#full-width
s, then assign the appropriate style:This finds all
#full-width .companies
, and selects just those.companies
, similar to how selectors are used to target specific elements in standard in CSS.Then it uses
.parents
to "backtrack" and select ALL parents of.companies
,but filters those results to keep only
#fill-width
elements, so that in the end,it only selects a
#full-width
element if it has a.companies
class descendant.Finally, it assigns a new CSS (
width
) value to the resulting element.jQuery Reference Docs:
$() or jQuery(): DOM element.
.find: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
.parents: Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector (filters the results to only include the listed elements/selectors).
.css: Set one or more CSS properties for the set of matched elements.
您可以使用
:has()
如下。我用它来修复重叠的引导模式,如下所示。如果有多个,任何先前的模态都会被隐藏。
You can use
:has()
as following.I used this for fixing overlapping bootstrap modals as follows. Any previous modals will be hidden if there are multiple.
我找到了最简单的解决方案。它可能仅适用于您正在做的事情。
假设您想将鼠标悬停在“sibling_2”上以更改以下示例中的“sibling_1”:
由于没有先前的元素选择器,您可以简单地切换“sibling_1”和“sibling_2”并应用,以便它们看起来相同。
现在您可以像这样选择它们。
I've found the easiest solution. It might only apply based on what you're doing.
Let's say you want to hover on "sibling_2" to change "sibling_1" in the example below:
Since there's no previous element selector you can simply switch 'sibling_1' and 'sibling_2' around and apply so they look the same.
Now you can select them like that.
不幸的是,没有“前一个”同级选择器,但是您仍然可以通过使用定位(例如向右浮动)来获得相同的效果。这取决于您想要做什么。
就我而言,我想要一个主要是 CSS 5 星级的评级系统。我需要给前面的星星着色(或交换图标)。通过向右浮动每个元素,我基本上得到了相同的效果(因此星星的 html 必须“向后”编写)。
我在这个例子中使用 FontAwesome 并在 fa-star-o 和 fa-star 的 unicode 之间交换
http://fortawesome.github.io/Font-Awesome/
CSS:
HTML:
(40)
JSFiddle: http://jsfiddle.net/andrewleyva/88j0105g/
There is no "previous" sibling selector unfortunately, but you can possibly still get the same effect by using positioning (e.g. float right). It depends on what you are trying to do.
In my case, I wanted a primarily CSS 5-star rating system. I would need to color (or swap the icon of) the previous stars. By floating each element right, I am essentially getting the same effect (the html for the stars thus must be written 'backwards').
I'm using FontAwesome in this example and swapping between the unicodes of fa-star-o and fa-star
http://fortawesome.github.io/Font-Awesome/
CSS:
HTML:
(40)
JSFiddle: http://jsfiddle.net/andrewleyva/88j0105g/
根据您的具体目标,有一种方法可以在不使用父选择器的情况下实现父选择器的有用性(即使存在)...
假设我们有:
我们可以做什么来制作袜子块(包括袜子颜色)使用间距在视觉上脱颖而出?
什么会很好但不存在:
存在什么:
这将所有锚链接设置为顶部有 15px 边距,并将其重置为 0(对于 LI 内没有 UL 元素(或其他标签)的锚链接)。
Depending on your exact objective, there is a way to achieve the usefulness of a parent selector without using one (even if one were to exist)...
Say we have:
What can we do to make the Socks block (including sock colours) stand out visually using spacing?
What would be nice but doesn't exist:
What does exist:
This sets all anchor links to have 15px margin on the top and resets it back to 0 for those with no UL elements (or other tags) inside LIs.
没有,但是有。
如果必须将标签放在输入之前,只需将标签放在输入之后,并保留输入 em>标签 & div 内的 input,并将 div 的样式设置如下:
现在,您可以应用 css 中可用的标准下一个同级样式选项,并且看起来就像您正在使用上一个同级样式一样。
There isn't, and there is.
If you must place the label before the input, just place the label after the input and keep both the label & the input inside a div, and style the div as following :
Now you can apply the standard next sibling styling options available in css, and it will appear like you are using a previous sibling styling.
我通过将元素放入 Flexbox 中然后使用 Flex-direction: column-reverse 解决了这个问题。
然后我必须手动反转 HTML 中的元素(以相反的顺序放置它们),它看起来很正常并且有效!
I fixed this problem by putting my elements in a flexbox and then using
flex-direction: column-reverse
.Then I had to invert my elements in the HTML manually (put them in reverse order), and it looked normal and it worked!
css中实际上没有选择器可以选择前一个同级。但可以使用某些技巧。
例如,如果您想在将鼠标悬停在任何元素上时更改前一个元素的样式,则可以使用以下命令:
在这种情况下,如果您将鼠标悬停在 .next-element 上,则 .element 的样式将按照您上面的定义进行更改
There is actually no selector that can select the previous sibling in css. But it is possible to use certain tricks.
For example, if you want to change the style of the previous element when you hover over any element, you can use this:
In this situation if you hover over .next-element the style of .element will change as you defined above
我需要一个解决方案来选择前一个同级 tr。我使用 React 和 Styled-components 想出了这个解决方案。这不是我的确切解决方案(这是几个小时后的记忆)。我知道 setHighlighterRow 函数有一个缺陷。
OnMouseOver 一行会将行索引设置为 state,并使用新的背景颜色重新渲染前一行
I needed a solution to select the previous sibling tr. I came up with this solution using React and Styled-components. This is not my exact solution (This is from memory, hours later). I know there is a flaw in the setHighlighterRow function.
OnMouseOver a row will set the row index to state, and rerender the previous row with a new background color
没有这样的选择器,但在 DOM API 中有一个相当只读的属性
Node.previousSibling
There is no such selector, but in the DOM API has a pretty read-only property
Node.previousSibling
我有一个类似的问题,发现所有这种性质的问题都可以解决如下:
这样您就可以设置当前的、以前的项目(所有项目都被当前和下一个项目覆盖)和下一个项目的样式。
示例:
希望它对某人有帮助。
I had a similar problem and found out that all problem of this nature can be solved as follows:
and this way you'll be able to style your current, previous items(all items overridden with current and next items) and your next items.
example:
Hope it helps someone.
这是类似问题的链接
CSS 选择所有以前的兄弟姐妹进行星级评级
因此,我使用每个人的回复的一部分来发布我的解决方案,任何人都可以将其用作参考,并可能提出改进建议。
here is the link for a similar question
CSS select all previous siblings for a star rating
So I post my solution using bits of everyones responses and anyone can use it as reference and possibliy recommend improvements.
我找到了一个方法,试试这个:
如果.prev_item是.next_item之前的兄弟,它会改变它的颜色;
I found a way, try this:
It will change the color of .prev_item if it is the sibling before .next_item;
对于我的用例,需要更改焦点上的先前元素样式,并将鼠标悬停在父元素中仅具有 2 个项目。为此,使用了
:focus-within
和:hover
伪类。就像这样在焦点/悬停事件发生时选择
For my use case was needed to change previous element style on focus and hover only having 2 items in parent element. to do so used
:focus-within
and:hover
pseudo-classes.like so selecting whenever focus/hover event occurs