是否有“以前的兄弟姐妹”?选择器?

发布于 08-13 07:06 字数 64 浏览 10 评论 0原文

加号选择器 (+) 用于选择下一个相邻的同级。

前一个兄弟姐妹有同等的吗?

The plus sign selector (+) is for selecting the next adjacent sibling.

Is there an equivalent for the previous sibling?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

谁人与我共长歌 2024-08-20 07:06:51

不,没有“前一个兄弟”选择器。

与此相关的是,~ 用于一般后继同级元素(意味着该元素位于该元素之后,但不一定紧随其后),并且是一个 CSS3 选择器。 + 代表下一个同级,是 CSS2.1。

请参阅 选择器级别 35.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.

无尽的现实 2024-08-20 07:06:51

4 级选择器建议 :has()允许您通过以下方式选择前一个同级:

previous:has(+ next) {}

或(对于一般的前一个同级而不是相邻的):

previous:has(~ next) {}

它具有出色的 浏览器支持

Selectors level 4 proposes :has() which allows you to select a previous sibling with:

previous:has(+ next) {}

or (for a general previous sibling rather than adjacent one):

previous:has(~ next) {}

It has excellent browser support.

挽清梦 2024-08-20 07:06:51

我找到了一种对所有以前的兄弟姐妹进行样式设置的方法(与 ~ 相反),该方法可能会根据您的需要而起作用。

假设您有一个链接列表,当鼠标悬停在其中一个链接上时,所有之前的链接都应该变成红色。你可以这样做:

/* default link color is blue */
.parent a {
  color: blue;
}

/* prev siblings should be red */
.parent:hover a {
  color: red;
}
.parent a:hover,
.parent a:hover ~ a {
  color: blue;
}
<div class="parent">
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
</div>

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:

/* default link color is blue */
.parent a {
  color: blue;
}

/* prev siblings should be red */
.parent:hover a {
  color: red;
}
.parent a:hover,
.parent a:hover ~ a {
  color: blue;
}
<div class="parent">
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
  <a href="#">link</a>
</div>

许你一世情深 2024-08-20 07:06:51

考虑 Flex 和网格布局的 order 属性。

我将在下面的示例中重点关注 Flexbox,但相同的概念也适用于 Grid。


使用 Flexbox,可以模拟以前的同级选择器。

特别是,flex < code>order 属性可以在屏幕上移动元素。

这是一个例子:

您希望当元素 B 悬停时元素 A 变为红色。

<前><代码>

    ;

  • A
  • B

步骤

  1. ul 设为 Flex 容器。

    ul { 显示:flex; }
    

  1. 反转标记中同级的顺序。

    <前><代码>

      ;

    • B
    • A

  1. 使用同级选择器来定位元素 A(~+ 就可以了)。

    li:hover + li { 背景颜色: 红色; }
    

  1. 使用 flex order 属性可恢复视觉显示上同级的顺序。

    li:last-child { 顺序:-1; }
    

...瞧!前一个同级选择器诞生了(或者至少是模拟的)。

这是完整的代码:

ul {
    display: flex;
}

li:hover + li {
    background-color: red;
}

li:last-child {
    order: -1;
}

/* non-essential decorative styles */
li {
    height: 200px;
    width: 200px;
    background-color: aqua;
    margin: 5px;
    list-style-type: none;
    cursor: pointer;
}
<ul>
    <li>B</li>
    <li>A</li>
</ul>

来自弹性盒规范:

5.4。显示顺序:order 属性

默认情况下,Flex 项目的显示和布局顺序与其在源文档中的显示顺序相同。这
order 属性可用于更改此顺序。

order 属性通过将 Flex 项目分配给序数组来控制 Flex 项目在 Flex 容器中出现的顺序。它采用单个 值,该值指定弹性项目的序数组
属于。

所有 Flex 项目的初始 order 值为 0。

另请参阅 顺序


使用 flex order 属性创建的“前一个同级选择器”示例。

.container { display: flex; }

.box5 { order: 1; }    
.box5:hover + .box4 { background-color: orangered; font-size: 1.5em; }

.box6 { order: -4; }
.box7 { order: -3; }
.box8 { order: -2; }
.box9 { order: -1; }
.box9:hover ~ :not(.box12):nth-child(-1n+5) { background-color: orangered;
                                              font-size: 1.5em; }
.box12 { order: 2; }
.box12:hover ~ :nth-last-child(-1n+2) { background-color: orangered;
                                        font-size: 1.5em; }
.box21 { order: 1; }
.box21:hover ~ .box { background-color: orangered; font-size: 1.5em; }

/* non-essential decorative styles */
.container {
    padding: 5px;
    background-color: #888;
}
.box {
    height: 50px;
    width: 75px;
    margin: 5px;
    background-color: lightgreen;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    cursor: pointer;
}
<p>
Using the flex <code>order</code> property to construct a previous sibling selector
</p>

<div class="container">
    <div class="box box1"><span>1</span></div>
    <div class="box box2"><span>2</span></div>
    <div class="box box3"><span>3</span></div>
    <div class="box box5"><span>HOVER ME</span></div>
    <div class="box box4"><span>4</span></div>
</div>

<br>

<div class="container">
    <div class="box box9"><span>HOVER ME</span></div>
    <div class="box box12"><span>HOVER ME</span></div>
    <div class="box box6"><span>6</span></div>
    <div class="box box7"><span>7</span></div>
    <div class="box box8"><span>8</span></div>
    <div class="box box10"><span>10</span></div>
    <div class="box box11"><span>11</span></div>
</div>

<br>

<div class="container">
    <div class="box box21"><span>HOVER ME</span></div>
    <div class="box box13"><span>13</span></div>
    <div class="box box14"><span>14</span></div>
    <div class="box box15"><span>15</span></div>
    <div class="box box16"><span>16</span></div>
    <div class="box box17"><span>17</span></div>
    <div class="box box18"><span>18</span></div>
    <div class="box box19"><span>19</span></div>
    <div class="box box20"><span>20</span></div>
</div>

jsFiddle


旁注 – 关于 CSS

Flexbox 的两个过时的信念正在粉碎人们长期以来的信念关于CSS。

其中一个信念是CSS 中不可能存在前一个同级选择器

说这种信念很普遍是轻描淡写的。以下是 Stack Overflow 上的相关问题示例:

如上所述,这种信念并不完全正确。可以使用 flex order 属性在 CSS 中模拟先前的同级选择器。

z-index 神话

另一个长期存在的信念是 z-index 仅适用于定位元素。

事实上,该规范的最新版本 - W3C 编辑草案 – 仍然断言这是真的:

9.9.1 指定堆栈级别:z -索引
属性

z 索引

  • 值:自动 | |继承
  • 首字母:自动
  • 适用于:定位元素
  • 继承:否
  • 百分比:不适用
  • 媒体:视觉
  • 计算值:按照规定

(添加强调)

然而,实际上,这些信息已经过时且不准确。

弹性项目网格项position 为 static,strong> 也可以创建堆叠上下文。

4.3。弹性项目 Z 排序

Flex 项目的绘制与内联块完全相同,只是使用顺序修改的文档顺序来代替原始顺序
文档顺序和除 auto 之外的 z-index 值会创建堆叠上下文,即使 positionstatic。< /p>

5.4。 Z 轴排序:z-index 属性

网格项的绘制顺序与内联块完全相同,只是顺序修改后的文档顺序为
用于代替原始文档顺序,并且 auto 之外的 z-index 值会创建堆叠上下文,即使
位置静态

以下是 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:

You want element A to turn red when element B is hovered.

<ul>
    <li>A</li>
    <li>B</li>
</ul>

STEPS

  1. Make the ul a flex container.

    ul { display: flex; }
    

  1. Reverse the order of siblings in the mark-up.

    <ul>
       <li>B</li>
       <li>A</li>
    </ul>
    

  1. Use a sibling selector to target Element A (~ or + will do) .

    li:hover + li { background-color: red; }
    

  1. Use the flex order property to restore the order of siblings on the visual display.

    li:last-child { order: -1; }
    

...and voilà! A previous sibling selector is born (or at least simulated).

Here's the full code:

ul {
    display: flex;
}

li:hover + li {
    background-color: red;
}

li:last-child {
    order: -1;
}

/* non-essential decorative styles */
li {
    height: 200px;
    width: 200px;
    background-color: aqua;
    margin: 5px;
    list-style-type: none;
    cursor: pointer;
}
<ul>
    <li>B</li>
    <li>A</li>
</ul>

From the flexbox spec:

5.4. Display Order: the order property

Flex items are, by default, displayed and laid out in the same order as they appear in the source document. The
order property can be used to change this ordering.

The order property controls the order in which flex items appear within the flex container, by assigning them to ordinal groups. It takes a single <integer> value, which specifies which ordinal group the flex item
belongs to.

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.

.container { display: flex; }

.box5 { order: 1; }    
.box5:hover + .box4 { background-color: orangered; font-size: 1.5em; }

.box6 { order: -4; }
.box7 { order: -3; }
.box8 { order: -2; }
.box9 { order: -1; }
.box9:hover ~ :not(.box12):nth-child(-1n+5) { background-color: orangered;
                                              font-size: 1.5em; }
.box12 { order: 2; }
.box12:hover ~ :nth-last-child(-1n+2) { background-color: orangered;
                                        font-size: 1.5em; }
.box21 { order: 1; }
.box21:hover ~ .box { background-color: orangered; font-size: 1.5em; }

/* non-essential decorative styles */
.container {
    padding: 5px;
    background-color: #888;
}
.box {
    height: 50px;
    width: 75px;
    margin: 5px;
    background-color: lightgreen;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    cursor: pointer;
}
<p>
Using the flex <code>order</code> property to construct a previous sibling selector
</p>

<div class="container">
    <div class="box box1"><span>1</span></div>
    <div class="box box2"><span>2</span></div>
    <div class="box box3"><span>3</span></div>
    <div class="box box5"><span>HOVER ME</span></div>
    <div class="box box4"><span>4</span></div>
</div>

<br>

<div class="container">
    <div class="box box9"><span>HOVER ME</span></div>
    <div class="box box12"><span>HOVER ME</span></div>
    <div class="box box6"><span>6</span></div>
    <div class="box box7"><span>7</span></div>
    <div class="box box8"><span>8</span></div>
    <div class="box box10"><span>10</span></div>
    <div class="box box11"><span>11</span></div>
</div>

<br>

<div class="container">
    <div class="box box21"><span>HOVER ME</span></div>
    <div class="box box13"><span>13</span></div>
    <div class="box box14"><span>14</span></div>
    <div class="box box15"><span>15</span></div>
    <div class="box box16"><span>16</span></div>
    <div class="box box17"><span>17</span></div>
    <div class="box box18"><span>18</span></div>
    <div class="box box19"><span>19</span></div>
    <div class="box box20"><span>20</span></div>
</div>

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 Myth

Another 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:

9.9.1 Specifying the stack level: the z-index
property

z-index

  • Value: auto | | inherit
  • Initial: auto
  • Applies to: positioned elements
  • Inherited: no
  • Percentages: N/A
  • Media: visual
  • Computed value: as specified

(emphasis added)

In reality, however, this information is obsolete and inaccurate.

Elements that are flex items or grid items can create stacking contexts even when position is static.

4.3. Flex Item Z-Ordering

Flex items paint exactly the same as inline blocks, except that order-modified document order is used in place of raw
document order, and z-index values other than auto create a stacking context even if position is static.

5.4. Z-axis Ordering: the z-index property

The painting order of grid items is exactly the same as inline blocks, except that order-modified document order is
used in place of raw document order, and z-index values other than auto create a stacking context even if
position is static.

Here's a demonstration of z-index working on non-positioned flex items: https://jsfiddle.net/m0wddwxs/

☆獨立☆ 2024-08-20 07:06:51

我也有同样的问题,但后来我有一个“呃”时刻。而不是写

x ~ y

write

y ~ x

显然这匹配“x”而不是“y”,但它回答了“是否有匹配?”问题,简单的 DOM 遍历可能比在 javascript 中循环更有效地让你找到正确的元素。

我意识到原来的问题是一个 CSS 问题,所以这个答案可能完全无关,但其他 Javascript 用户可能会像我一样通过搜索偶然发现这个问题。

I had the same question, but then I had a "duh" moment. Instead of writing

x ~ y

write

y ~ x

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.

明媚如初 2024-08-20 07:06:51

没有“前一个选择器”,但您可以使用 :not~ (“后选择器”)的组合。没有相反的顺序,没有 JavaScript。

.parent a{
  color: blue
}

.parent a.active{
  color: red
}

.parent a:not(.parent a.active ~ a){
  color: red
}
<div class="parent">
  <a href="">link</a>
  <a href="">link</a>
  <a href="" class="active">link</a>
  <a href="">link</a>
  <a href="">link</a>
</div>

我认为我的方法比“设置所有 div 的样式,而不是删除 div 之后的样式”,或者使用 javascript,或者使用相反的顺序更直接。

There's not "previous selector", but you can use the combination of :not and ~ ("after selector"). No reverse order, no javascript.

.parent a{
  color: blue
}

.parent a.active{
  color: red
}

.parent a:not(.parent a.active ~ a){
  color: red
}
<div class="parent">
  <a href="">link</a>
  <a href="">link</a>
  <a href="" class="active">link</a>
  <a href="">link</a>
  <a href="">link</a>
</div>

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.

紫轩蝶泪 2024-08-20 07:06:51

三个技巧
基本上,反转 HTML 中元素的 HTML 顺序
并使用 ~ Next brothers 运算符:

1. 使用 CSS Flex 和 row-reverse

.reverse {
  display: inline-flex;
  flex-direction: row-reverse;
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background:gold;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

2.使用带有方向的Flex:RTL

.reverse {
  display: inline-flex;
  direction: rtl;
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background: red;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

3.使用右浮动

.reverse { 
  display: inline-block;
}
.reverse span{
  float: right; 
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background: red;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

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

.reverse {
  display: inline-flex;
  flex-direction: row-reverse;
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background:gold;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

2. Using Flex with direction: RTL

.reverse {
  display: inline-flex;
  direction: rtl;
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background: red;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

3. Using float right

.reverse { 
  display: inline-block;
}
.reverse span{
  float: right; 
}
.reverse span:hover ~ span { /* On SPAN hover target its "previous" elements */
  background: red;
}
Hover a SPAN and see the previous elements being styled!<br>

<div class="reverse">
  <!-- Reverse the order of inner elements -->
  <span>5</span>
  <span>4</span>
  <span>3</span>
  <span>2</span>
  <span>1</span>
</div>

冰火雁神 2024-08-20 07:06:51

+ 用于下一个同级。是否有与前一个相当的内容
兄弟姐妹?

您可以使用两个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
div {
  display: inline-block;
  width: 60px;
  height: 100px;
  color: rgb(255, 255, 255);
  background-color: rgb(255, 0, 0);
  text-align: center;
  vertical-align: top;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.6s ease-out;
}

code {
  display: block;
  margin: 4px;
  font-size: 24px;
  line-height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
}

div:nth-of-type(-n+4) {
  background-color: rgb(0, 0, 255);
}

div:nth-of-type(n+3):nth-of-type(-n+6) {
  opacity: 1;
}

.any-subsequent:hover ~ div,
.immediate-subsequent:hover + div,
.any-previous:hover ! div,
.immediate-previous:hover ? div {
  opacity: 1;
}
<h2>Hover over any of the blocks below</h2>

<div></div>
<div></div>

<div class="immediate-previous">Hover for <code>?</code> selector</div>
<div class="any-previous">Hover for <code>!</code> selector</div>
<div class="any-subsequent">Hover for <code>~</code> selector</div>
<div class="immediate-subsequent">Hover for <code>+</code> selector</div>

<div></div>
<div></div>

<script src="https://rouninmedia.github.io/axe/axe.js"></script>

+ is for the next sibling. Is there an equivalent for the previous
sibling?

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 selector

In 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 subsequent div
  • .immediate-subsequent:hover + div selects the immediate subsequent div
  • .any-previous:hover ! div selects any previous div
  • .immediate-previous:hover ? div selects the immediate previous div

div {
  display: inline-block;
  width: 60px;
  height: 100px;
  color: rgb(255, 255, 255);
  background-color: rgb(255, 0, 0);
  text-align: center;
  vertical-align: top;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.6s ease-out;
}

code {
  display: block;
  margin: 4px;
  font-size: 24px;
  line-height: 24px;
  background-color: rgba(0, 0, 0, 0.5);
}

div:nth-of-type(-n+4) {
  background-color: rgb(0, 0, 255);
}

div:nth-of-type(n+3):nth-of-type(-n+6) {
  opacity: 1;
}

.any-subsequent:hover ~ div,
.immediate-subsequent:hover + div,
.any-previous:hover ! div,
.immediate-previous:hover ? div {
  opacity: 1;
}
<h2>Hover over any of the blocks below</h2>

<div></div>
<div></div>

<div class="immediate-previous">Hover for <code>?</code> selector</div>
<div class="any-previous">Hover for <code>!</code> selector</div>
<div class="any-subsequent">Hover for <code>~</code> selector</div>
<div class="immediate-subsequent">Hover for <code>+</code> selector</div>

<div></div>
<div></div>

<script src="https://rouninmedia.github.io/axe/axe.js"></script>

御守 2024-08-20 07:06:51

2023 年情况发生了变化。现在有了这样的选择器:

    // 1 item before
    :has(+ .item:hover) {
        ...
    }

如果你想选择之前的 3 个项目,你可以这样做:

    // 3 items before
    :has(+ .item:hover),
    :has(+ .item + .item:hover),
    :has(+ .item + .item + .item:hover) {
        ...
    }

在此处查看我的演示 https://codepen.io/ro31337/pen/YzJbEZv

Things have changed in 2023. Now there is such selector:

    // 1 item before
    :has(+ .item:hover) {
        ...
    }

If you want to select 3 items before, you do something like:

    // 3 items before
    :has(+ .item:hover),
    :has(+ .item + .item:hover),
    :has(+ .item + .item + .item:hover) {
        ...
    }

See my demo here https://codepen.io/ro31337/pen/YzJbEZv

玉环 2024-08-20 07:06:51

另一种 Flexbox 解决方案

您可以使用 HTML 中元素的相反顺序。然后,除了使用Michael_B的答案中的order之外,您还可以使用flex-direction: row -reverse;flex-direction: column-reverse; 取决于您的布局。

工作样本:

.flex {
  display: flex;
  flex-direction: row-reverse;
   /* Align content at the "reversed" end i.e. beginning */
  justify-content: flex-end;
}

/* On hover target its "previous" elements */
.flex-item:hover ~ .flex-item {
  background-color: lime;
}

/* styles just for demo */
.flex-item {
  background-color: orange;
  color: white;
  padding: 20px;
  font-size: 3rem;
  border-radius: 50%;
}
<div class="flex">
  <div class="flex-item">5</div>
  <div class="flex-item">4</div>
  <div class="flex-item">3</div>
  <div class="flex-item">2</div>
  <div class="flex-item">1</div>
</div>

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 use flex-direction: row-reverse; or flex-direction: column-reverse; depending on your layout.

Working sample:

.flex {
  display: flex;
  flex-direction: row-reverse;
   /* Align content at the "reversed" end i.e. beginning */
  justify-content: flex-end;
}

/* On hover target its "previous" elements */
.flex-item:hover ~ .flex-item {
  background-color: lime;
}

/* styles just for demo */
.flex-item {
  background-color: orange;
  color: white;
  padding: 20px;
  font-size: 3rem;
  border-radius: 50%;
}
<div class="flex">
  <div class="flex-item">5</div>
  <div class="flex-item">4</div>
  <div class="flex-item">3</div>
  <div class="flex-item">2</div>
  <div class="flex-item">1</div>
</div>

小红帽 2024-08-20 07:06:51

目前还没有官方方法可以做到这一点,但您可以使用一些小技巧来实现这一点!请记住,它是实验性的,并且有一些限制......
(如果您担心导航器兼容性,请检查此链接

您可以做的是使用CSS3选择器:伪类称为nth-child()

#list>* {
  display: inline-block;
  padding: 20px 28px;
  margin-right: 5px;
  border: 1px solid #bbb;
  background: #ddd;
  color: #444;
  margin: 0.4em 0;
}

#list :nth-child(-n+4) {
  color: #600b90;
  border: 1px dashed red;
  background: orange;
}
<p>The oranges elements are the previous sibling li selected using li:nth-child(-n+4)</p>

<div id="list">
  <span>1</span><!-- this will be selected -->
  <p>2</p><!-- this will be selected -->
  <p>3</p><!-- this will be selected -->
  <div>4</div><!-- this will be selected -->
  <div>5</div>
  <p>6</p>
  <p>7</p>
  <p>8</p>
  <p>9</p>
</div>

限制

  • 您不能根据下一个元素的类来选择前一个元素
  • 这对于伪类来说是相同的

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()

#list>* {
  display: inline-block;
  padding: 20px 28px;
  margin-right: 5px;
  border: 1px solid #bbb;
  background: #ddd;
  color: #444;
  margin: 0.4em 0;
}

#list :nth-child(-n+4) {
  color: #600b90;
  border: 1px dashed red;
  background: orange;
}
<p>The oranges elements are the previous sibling li selected using li:nth-child(-n+4)</p>

<div id="list">
  <span>1</span><!-- this will be selected -->
  <p>2</p><!-- this will be selected -->
  <p>3</p><!-- this will be selected -->
  <div>4</div><!-- this will be selected -->
  <div>5</div>
  <p>6</p>
  <p>7</p>
  <p>8</p>
  <p>9</p>
</div>

Limitations

  • You can't select previous elements based on the classes of the next elements
  • This is the same for pseudo classes
人间☆小暴躁 2024-08-20 07:06:51

您可以使用双重否定

SELECTOR:not([SELECTOR]FILTER):not([SELECTOR]FILTER + SELECTOR) { ... }

SELECTOR 替换为 TAG.CLASS (使用 #ID 可能过于具体)。
FILTER 替换为其他 :PSUEDO-SELECTOR (我只尝试过 :hover)或 .CLASS (更多关于通过 Javascript 进行切换的信息)。

由于典型用法可能依赖于悬停(请参阅下面的示例)

/* Effect only limited when hovering */
TAG.CLASS:not(TAG.CLASS:hover):not(TAG.CLASS:hover + TAG.CLASS) {}
/* Effect only applied when hovering */
PARENT.CLASS:hover > CHILD.CLASS:not(CHILD.CLASS:hover):not(CHILD.CLASS:hover + CHILD.CLASS) {}

/* Solution */
div.parent:hover > div.child:not(:hover):not(:hover ~ .child)  {
    background-color:red;
    border-radius:1.5em;
}
div.parent:hover > div.child:not(:hover):not(:hover ~ .child) > div {
    background-color:yellow;
}

/* Make pretty (kinda) */
div.parent {
  width:9em;
  height:9em;
  /* Layout */
  display:grid;
  grid-template-columns : auto auto auto;
  grid-template-rows : auto auto auto;
}
div.child {
  /* Dimensions */
  height:3em;
  width:3em;
  /* Layout */
  position:relative;
  /* Cursor */
  cursor: pointer;
  /* Presentation */
  border: 1px black solid;
  border-radius:1.5em;
}
.star {
  /* Dimensions */
  width: 2.5em;
  height: 2.5em;
  /* Placement */
  position:absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  /* Geometry */
  -webkit-clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  /* Presentation */
  background-color: lightgrey;
}
div.child:hover {
    /* Presentation */
    background-color:yellow;
    border-radius:1.5em;
}
div.child:hover > div.star {
    /* Presentation */
    background-color:red;
}
<div class="parent">
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
 </div>

You could use double negation

SELECTOR:not([SELECTOR]FILTER):not([SELECTOR]FILTER + SELECTOR) { ... }

Replace SELECTOR with either the TAG 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)

/* Effect only limited when hovering */
TAG.CLASS:not(TAG.CLASS:hover):not(TAG.CLASS:hover + TAG.CLASS) {}
/* Effect only applied when hovering */
PARENT.CLASS:hover > CHILD.CLASS:not(CHILD.CLASS:hover):not(CHILD.CLASS:hover + CHILD.CLASS) {}

/* Solution */
div.parent:hover > div.child:not(:hover):not(:hover ~ .child)  {
    background-color:red;
    border-radius:1.5em;
}
div.parent:hover > div.child:not(:hover):not(:hover ~ .child) > div {
    background-color:yellow;
}

/* Make pretty (kinda) */
div.parent {
  width:9em;
  height:9em;
  /* Layout */
  display:grid;
  grid-template-columns : auto auto auto;
  grid-template-rows : auto auto auto;
}
div.child {
  /* Dimensions */
  height:3em;
  width:3em;
  /* Layout */
  position:relative;
  /* Cursor */
  cursor: pointer;
  /* Presentation */
  border: 1px black solid;
  border-radius:1.5em;
}
.star {
  /* Dimensions */
  width: 2.5em;
  height: 2.5em;
  /* Placement */
  position:absolute;
  top: 50%;
  left: 50%;
  transform:translate(-50%,-50%);
  /* Geometry */
  -webkit-clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  clip-path: polygon(
    50% 0%,
    63% 38%,
    100% 38%,
    69% 59%,
    82% 100%,
    50% 75%,
    18% 100%,
    31% 59%,
    0% 38%,
    37% 38%
  );
  /* Presentation */
  background-color: lightgrey;
}
div.child:hover {
    /* Presentation */
    background-color:yellow;
    border-radius:1.5em;
}
div.child:hover > div.star {
    /* Presentation */
    background-color:red;
}
<div class="parent">
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
  <div class="child" href="#"><div class="star"></div></div>
 </div>

郁金香雨 2024-08-20 07:06:51

我的要求是在 @Quentin 的答案的帮助下选择当前悬停项目的前一个和后两个兄弟姐妹,我选择了前一个兄弟姐妹。

.child{
  width: 25px;
  height: 25px;
}

.child:hover {
    background:blue;
}

 .child:has( + .child:hover) {
  background: yellow;
}

.child:has(+ .child + .child:hover){
  background:green;
}

.child:hover + .child {
  background: red;
}

.child:hover + .child + .child {
  background: magenta;
}
<ul class="parent">
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
</ul>

选择所有先前的兄弟姐妹

.child {
    width: 25px;
    height: 25px;
}

.child:hover {
    background: blue;
}

.child:has(~ .child:hover) {
    background: red;
}
<ul class="parent">
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
</ul>

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.

.child{
  width: 25px;
  height: 25px;
}

.child:hover {
    background:blue;
}

 .child:has( + .child:hover) {
  background: yellow;
}

.child:has(+ .child + .child:hover){
  background:green;
}

.child:hover + .child {
  background: red;
}

.child:hover + .child + .child {
  background: magenta;
}
<ul class="parent">
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
</ul>

To select all previous siblings

.child {
    width: 25px;
    height: 25px;
}

.child:hover {
    background: blue;
}

.child:has(~ .child:hover) {
    background: red;
}
<ul class="parent">
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
  <li class="child"></li>
</ul>

蹲在坟头点根烟 2024-08-20 07:06:51

覆盖悬停时下一个兄弟姐妹的样式,以便看起来只有前一个兄弟姐妹在悬停时添加了样式。

ul li {
  color: red;
}

ul:hover li {
  color: blue;
}

ul:hover li:hover ~ li{
  color: red;
}
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>

Overriding the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.

ul li {
  color: red;
}

ul:hover li {
  color: blue;
}

ul:hover li:hover ~ li{
  color: red;
}
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>

丿*梦醉红颜 2024-08-20 07:06:51

如果您知道确切的位置,则可以基于 :nth-child() 排除所有后续同级。

ul li:not(:nth-child(n+3))

这将选择第三个之前的所有li(例如第一个和第二个)。但是,在我看来,这看起来很难看,而且用例非常紧张。

您还可以从右到左选择第 n 个子级:

ul li:nth-child(-n+2)

其作用相同。

If you know the exact position an :nth-child()-based exclusion of all following siblings would work.

ul li:not(:nth-child(n+3))

Which would select all lis 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:

ul li:nth-child(-n+2)

Which does the same.

涫野音 2024-08-20 07:06:51

不可以。通过 CSS 是不可能的。它牢记“级联”;-)。


但是,如果您能够将 JavaScript 添加到您的页面,那么一点 jQuery 就可以帮助您实现最终目标。
您可以使用 jQuery 的 find 对目标元素/类/id 执行“向前查找”,然后回溯以选择您的目标。
然后,您使用 jQuery 为您的元素重写 DOM (CSS)。

基于迈克·布兰特的回答
下面的 jQuery 片段可能会有所帮助。

$('p + ul').prev('p')

首先选择紧随

之后的所有


    然后它“回溯”以从该组

      中选择所有先前的

实际上,“前一个兄弟”已通过 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").find(".companies").parents("#full-width").css( "width", "300px" );

这会找到所有#full-width .companies,并仅选择那些 .companies,类似于如何使用选择器来定位 CSS 标准中的特定元素。
然后它使用 .parents 进行“回溯”并选择 .companies 的所有父级,
但过滤这些结果以仅保留 #fill-width 元素,因此最终,
如果它具有 .companies 类后代,它只会选择 #full-width 元素。
最后,它为结果元素分配一个新的 CSS (width) 值。

$(".parent").find(".change-parent").parents(".parent").css( "background-color", "darkred");
div {
  background-color: lightblue;
  width: 120px;
  height: 40px;
  border: 1px solid gray;
  padding: 5px;
}
.wrapper {
  background-color: blue;
  width: 250px;
  height: 165px;
}
.parent {
  background-color: green;
  width: 200px;
  height: 70px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="wrapper">

  <div class="parent">
    "parent" turns red
    <div class="change-parent">
    descendant: "change-parent"
    </div>
  </div>
  
  <div class="parent">
    "parent" stays green
    <div class="nope">
    descendant: "nope"
    </div>
  </div>
  
</div>
Target <b>"<span style="color:darkgreen">parent</span>"</b> to turn <span style="color:red">red</span>.<br>
<b>Only</b> if it <b>has</b> a descendant of "change-parent".<br>
<br>
(reverse cascade, look ahead, parent un-descendant)
</html>

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.

$('p + ul').prev('p')

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-widths.
Or I could select .companies that only followed a #full-width.
But I could not select only #full-widths 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-widths, then assign the appropriate style:

$("#full-width").find(".companies").parents("#full-width").css( "width", "300px" );

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.

$(".parent").find(".change-parent").parents(".parent").css( "background-color", "darkred");
div {
  background-color: lightblue;
  width: 120px;
  height: 40px;
  border: 1px solid gray;
  padding: 5px;
}
.wrapper {
  background-color: blue;
  width: 250px;
  height: 165px;
}
.parent {
  background-color: green;
  width: 200px;
  height: 70px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<div class="wrapper">

  <div class="parent">
    "parent" turns red
    <div class="change-parent">
    descendant: "change-parent"
    </div>
  </div>
  
  <div class="parent">
    "parent" stays green
    <div class="nope">
    descendant: "nope"
    </div>
  </div>
  
</div>
Target <b>"<span style="color:darkgreen">parent</span>"</b> to turn <span style="color:red">red</span>.<br>
<b>Only</b> if it <b>has</b> a descendant of "change-parent".<br>
<br>
(reverse cascade, look ahead, parent un-descendant)
</html>

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.

寄离 2024-08-20 07:06:51

您可以使用 :has() 如下。

.thePrevious:has(+ .theNextSibling)

我用它来修复重叠的引导模式,如下所示。如果有多个,任何先前的模态都会被隐藏。

.modal.show.modal--open:has(~ .modal.show.modal--open){
   opacity: 0;
 }

You can use :has() as following.

.thePrevious:has(+ .theNextSibling)

I used this for fixing overlapping bootstrap modals as follows. Any previous modals will be hidden if there are multiple.

.modal.show.modal--open:has(~ .modal.show.modal--open){
   opacity: 0;
 }
垂暮老矣 2024-08-20 07:06:51
/* Add a style to all the children, then undo the style to the target 
and sibling children of your target. */

ul>li {
  color: red;
}

ul>li.target,
ul>li.target~li {
  color: inherit;
}
<ul>
  <li>before</li>
  <li class="target">target</li>
  <li>after</li>
  <li>after</li>
</ul>

/* Add a style to all the children, then undo the style to the target 
and sibling children of your target. */

ul>li {
  color: red;
}

ul>li.target,
ul>li.target~li {
  color: inherit;
}
<ul>
  <li>before</li>
  <li class="target">target</li>
  <li>after</li>
  <li>after</li>
</ul>

じ违心 2024-08-20 07:06:51

我找到了最简单的解决方案。它可能仅适用于您正在做的事情。

假设您想将鼠标悬停在“sibling_2”上以更改以下示例中的“sibling_1”:

<div class='parent'>
  <div class='sibling_1'></div>
  <div class='sibling_2'></div>
</div>

由于没有先前的元素选择器,您可以简单地切换“sibling_1”和“sibling_2”并应用,以便它们看起来相同。

.parent {
  display: flex;
  flex-direction: row-reverse;
}

现在您可以像这样选择它们。

.sibling_1:hover ~ .sibling_2 {
  #your CSS
}

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:

<div class='parent'>
  <div class='sibling_1'></div>
  <div class='sibling_2'></div>
</div>

Since there's no previous element selector you can simply switch 'sibling_1' and 'sibling_2' around and apply so they look the same.

.parent {
  display: flex;
  flex-direction: row-reverse;
}

Now you can select them like that.

.sibling_1:hover ~ .sibling_2 {
  #your CSS
}

路还长,别太狂 2024-08-20 07:06:51

不幸的是,没有“前一个”同级选择器,但是您仍然可以通过使用定位(例如向右浮动)来获得相同的效果。这取决于您想要做什么。

就我而言,我想要一个主要是 CSS 5 星级的评级系统。我需要给前面的星星着色(或交换图标)。通过向右浮动每个元素,我基本上得到了相同的效果(因此星星的 html 必须“向后”编写)。

我在这个例子中使用 FontAwesome 并在 fa-star-o 和 fa-star 的 unicode 之间交换
http://fortawesome.github.io/Font-Awesome/

CSS:

.fa {
    display: inline-block;
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

/* set all stars to 'empty star' */
.stars-container {
    display: inline-block;      
}   

/* set all stars to 'empty star' */
.stars-container .star {
    float: right;
    display: inline-block;
    padding: 2px;
    color: orange;
    cursor: pointer;

}

.stars-container .star:before {
    content: "\f006"; /* fontAwesome empty star code */
}

/* set hovered star to 'filled star' */
.star:hover:before{
    content: "\f005"; /* fontAwesome filled star code */
}

/* set all stars after hovered to'filled star' 
** it will appear that it selects all after due to positioning */
.star:hover ~ .star:before {
    content: "\f005"; /* fontAwesome filled star code */
}

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:

.fa {
    display: inline-block;
    font-family: FontAwesome;
    font-style: normal;
    font-weight: normal;
    line-height: 1;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

/* set all stars to 'empty star' */
.stars-container {
    display: inline-block;      
}   

/* set all stars to 'empty star' */
.stars-container .star {
    float: right;
    display: inline-block;
    padding: 2px;
    color: orange;
    cursor: pointer;

}

.stars-container .star:before {
    content: "\f006"; /* fontAwesome empty star code */
}

/* set hovered star to 'filled star' */
.star:hover:before{
    content: "\f005"; /* fontAwesome filled star code */
}

/* set all stars after hovered to'filled star' 
** it will appear that it selects all after due to positioning */
.star:hover ~ .star:before {
    content: "\f005"; /* fontAwesome filled star code */
}

HTML:

(40)

JSFiddle: http://jsfiddle.net/andrewleyva/88j0105g/

凉风有信 2024-08-20 07:06:51

根据您的具体目标,有一种方法可以在不使用父选择器的情况下实现父选择器的有用性(即使存在)...

假设我们有:

<div>
  <ul>
    <li><a>Pants</a></li>
    <li><a>Socks</a></li>
    <ul>
      <li><a>White socks</a></li>
      <li><a>Blue socks</a></li>
    </ul>
  </ul>
</div>

我们可以做什么来制作袜子块(包括袜子颜色)使用间距在视觉上脱颖而出?

什么会很好但不存在:

ul li ul:parent {
  margin-top: 15px;
  margin-bottom: 15px;
}

存在什么:

li > a {
  margin-top: 15px;
  display: block;
}
li > a:only-child {
  margin-top: 0px;
}

这将所有锚链接设置为顶部有 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:

<div>
  <ul>
    <li><a>Pants</a></li>
    <li><a>Socks</a></li>
    <ul>
      <li><a>White socks</a></li>
      <li><a>Blue socks</a></li>
    </ul>
  </ul>
</div>

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:

ul li ul:parent {
  margin-top: 15px;
  margin-bottom: 15px;
}

What does exist:

li > a {
  margin-top: 15px;
  display: block;
}
li > a:only-child {
  margin-top: 0px;
}

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.

吲‖鸣 2024-08-20 07:06:51

没有,但是

如果必须将标签放在输入之前,只需将标签放在输入之后,并保留输入 em>标签 & div 内的 input,并将 div 的样式设置如下:

.input-box {
  display: flex;
  flex-direction: column-reverse;
}
<div class="input-box">
  <input
   id="email"
   class="form-item"           
   />

   <label for="email" class="form-item-header">                  
   E-Mail*                  
   </label>
</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 :

.input-box {
  display: flex;
  flex-direction: column-reverse;
}
<div class="input-box">
  <input
   id="email"
   class="form-item"           
   />

   <label for="email" class="form-item-header">                  
   E-Mail*                  
   </label>
</div>

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.

反话 2024-08-20 07:06:51

我通过将元素放入 Flexbox 中然后使用 Flex-direction: column-reverse 解决了这个问题。

然后我必须手动反转 HTML 中的元素(以相反的顺序放置它们),它看起来很正常并且有效!

<div style="display: flex; flex-direction: column-reverse">
  <a class="element2">Element 2</a>
  <a class="element1">Element 1</a>
</div>
...
<style>
  .element2:hover + element1 {
    ...
  }
</style>

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!

<div style="display: flex; flex-direction: column-reverse">
  <a class="element2">Element 2</a>
  <a class="element1">Element 1</a>
</div>
...
<style>
  .element2:hover + element1 {
    ...
  }
</style>
围归者 2024-08-20 07:06:51

css中实际上没有选择器可以选择前一个同级。但可以使用某些技巧。
例如,如果您想在将鼠标悬停在任何元素上时更改前一个元素的样式,则可以使用以下命令:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .element:has(+ .next-element:hover){
      /* here your style for .element */
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="element"></div>
    <div class="next-element"></div>
  </div>
</body>
</html>

在这种情况下,如果您将鼠标悬停在 .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:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .element:has(+ .next-element:hover){
      /* here your style for .element */
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="element"></div>
    <div class="next-element"></div>
  </div>
</body>
</html>

In this situation if you hover over .next-element the style of .element will change as you defined above

请止步禁区 2024-08-20 07:06:51

我需要一个解决方案来选择前一个同级 tr。我使用 React 和 Styled-components 想出了这个解决方案。这不是我的确切解决方案(这是几个小时后的记忆)。我知道 setHighlighterRow 函数有一个缺陷。

OnMouseOver 一行会将行索引设置为 state,并使用新的背景颜色重新渲染前一行

class ReactClass extends Component {
  constructor() {
    this.state = {
       highlightRowIndex: null
    }
  }

  setHighlightedRow = (index) => {
    const highlightRowIndex = index === null ? null : index - 1;
    this.setState({highlightRowIndex});
  }

  render() {
    return (
       <Table>
        <Tbody>
           {arr.map((row, index) => {
                const isHighlighted = index === this.state.highlightRowIndex
                return {
                    <Trow 
                        isHighlighted={isHighlighted}
                        onMouseOver={() => this.setHighlightedRow(index)}
                        onMouseOut={() => this.setHighlightedRow(null)}
                        >
                        ...
                    </Trow>
                }
           })}  
        </Tbody>   
       </Table>
    )
  }
}

const Trow = styled.tr`
    & td {
        background-color: ${p => p.isHighlighted ? 'red' : 'white'};
    }

    &:hover {
        background-color: red;
    }
`;

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

class ReactClass extends Component {
  constructor() {
    this.state = {
       highlightRowIndex: null
    }
  }

  setHighlightedRow = (index) => {
    const highlightRowIndex = index === null ? null : index - 1;
    this.setState({highlightRowIndex});
  }

  render() {
    return (
       <Table>
        <Tbody>
           {arr.map((row, index) => {
                const isHighlighted = index === this.state.highlightRowIndex
                return {
                    <Trow 
                        isHighlighted={isHighlighted}
                        onMouseOver={() => this.setHighlightedRow(index)}
                        onMouseOut={() => this.setHighlightedRow(null)}
                        >
                        ...
                    </Trow>
                }
           })}  
        </Tbody>   
       </Table>
    )
  }
}

const Trow = styled.tr`
    & td {
        background-color: ${p => p.isHighlighted ? 'red' : 'white'};
    }

    &:hover {
        background-color: red;
    }
`;
时光是把杀猪刀 2024-08-20 07:06:51

没有这样的选择器,但在 DOM API 中有一个相当只读的属性

Node.previousSibling

There is no such selector, but in the DOM API has a pretty read-only property

Node.previousSibling

浮云落日 2024-08-20 07:06:51

我有一个类似的问题,发现所有这种性质的问题都可以解决如下:

  1. 给你的所有项目一个风格。
  2. 为您选择的项目指定样式。
  3. 使用 + 或 ~ 为下一个项目指定样式。

这样您就可以设置当前的、以前的项目(所有项目都被当前和下一个项目覆盖)和下一个项目的样式。

示例:

/* all items (will be styled as previous) */
li {
  color: blue;
}

/* the item i want to distinguish */
li.milk {
  color: red;
}

/* next items */
li ~ li  {
  color: green;
}


<ul>
  <li>Tea</li>
  <li class="milk">Milk</li>
  <li>Juice</li>
  <li>others</li>
</ul>

希望它对某人有帮助。

I had a similar problem and found out that all problem of this nature can be solved as follows:

  1. give all your items a style.
  2. give your selected item a style.
  3. give next items a style using + or ~.

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:

/* all items (will be styled as previous) */
li {
  color: blue;
}

/* the item i want to distinguish */
li.milk {
  color: red;
}

/* next items */
li ~ li  {
  color: green;
}


<ul>
  <li>Tea</li>
  <li class="milk">Milk</li>
  <li>Juice</li>
  <li>others</li>
</ul>

Hope it helps someone.

↘紸啶 2024-08-20 07:06:51

这是类似问题的链接

CSS 选择所有以前的兄弟姐妹进行星级评级

因此,我使用每个人的回复的一部分来发布我的解决方案,任何人都可以将其用作参考,并可能提出改进建议。

// Just to check input value
// Consts
const starRadios = document.querySelectorAll('input[name="rating"]');

// EventListeners
starRadios.forEach((radio) => radio.addEventListener('change', getStarRadioValue));

// Get star radio value
function getStarRadioValue(event) { 
    alert(event.target.value) 
    // Do something with it
};
.star-rating {
  font-size: 1.5rem;
  unicode-bidi: bidi-override;
  direction: rtl;
  text-align: left;
}
.star-rating.editable label:hover {
  cursor: pointer;
}
.star-rating.editable .icon-star:hover,
.star-rating.editable .icon-star:hover ~ .icon-star {
  background-color: #fb2727 !important;
}

.icon-star {
  position: relative;
  background-color: #72747d;
  width: 32px;
  height: 32px;
  display: inline-block;
  transition: background-color 0.3s ease;
}
.icon-star.filled {
  background-color: #fb2727;
}

.icon-star > label {
  display: inline-block;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  position: absolute;
}

.icon-star > label > input[type="radio"] {
  position: absolute;
  top: 0;
  left: 0;
  transform: translateY(50%) translateX(50%);
  display: none;
}
<div class="star-rating editable">
  <span class="icon-star">
    <label>
      <input type="radio" name="rating"  value="5" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="4" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="3" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="2" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating"  value="1" />
    </label>
  </span>
</div>

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.

// Just to check input value
// Consts
const starRadios = document.querySelectorAll('input[name="rating"]');

// EventListeners
starRadios.forEach((radio) => radio.addEventListener('change', getStarRadioValue));

// Get star radio value
function getStarRadioValue(event) { 
    alert(event.target.value) 
    // Do something with it
};
.star-rating {
  font-size: 1.5rem;
  unicode-bidi: bidi-override;
  direction: rtl;
  text-align: left;
}
.star-rating.editable label:hover {
  cursor: pointer;
}
.star-rating.editable .icon-star:hover,
.star-rating.editable .icon-star:hover ~ .icon-star {
  background-color: #fb2727 !important;
}

.icon-star {
  position: relative;
  background-color: #72747d;
  width: 32px;
  height: 32px;
  display: inline-block;
  transition: background-color 0.3s ease;
}
.icon-star.filled {
  background-color: #fb2727;
}

.icon-star > label {
  display: inline-block;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  position: absolute;
}

.icon-star > label > input[type="radio"] {
  position: absolute;
  top: 0;
  left: 0;
  transform: translateY(50%) translateX(50%);
  display: none;
}
<div class="star-rating editable">
  <span class="icon-star">
    <label>
      <input type="radio" name="rating"  value="5" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="4" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="3" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating" value="2" />
    </label>
  </span>
  <span class="icon-star">
    <label>
      <input type="radio" name="rating"  value="1" />
    </label>
  </span>
</div>

滥情哥ㄟ 2024-08-20 07:06:51

我找到了一个方法,试试这个:

.prev_item:has(+ .next_item) {
  color: red;
}

如果.prev_item.next_item之前的兄弟,它会改变它的颜色;

I found a way, try this:

.prev_item:has(+ .next_item) {
  color: red;
}

It will change the color of .prev_item if it is the sibling before .next_item;

难以启齿的温柔 2024-08-20 07:06:51

对于我的用例,需要更改焦点上的先前元素样式,并将鼠标悬停在父元素中仅具有 2 个项目。为此,使用了 :focus-within:hover 伪类。

就像这样在焦点/悬停事件发生时选择

.root-element:hover .element-to-style { background-color: red;} 
.root-element:focus-within .element-to-style { background-color: green;} 
<div class="root-element">
<span class="element-to-style"> TextFocused</span>
<input type="text" placeholder="type To Style"/>

</div>

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

.root-element:hover .element-to-style { background-color: red;} 
.root-element:focus-within .element-to-style { background-color: green;} 
<div class="root-element">
<span class="element-to-style"> TextFocused</span>
<input type="text" placeholder="type To Style"/>

</div>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文