如何将 css 规则应用于 HTML 中的上一个和下一个元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9732915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:09:55  来源:igfitidea点击:

how to apply css rule to the previous and the next element in HTML?

htmlcssbrowsercross-browserstylesheet

提问by CRISHK Corporation

For example:

例如:

You have this:

你有这个:

<ul>
 <li>zero</li>
 <li>one</li>
 <li class="selected">two</li>
 <li>three</li>
 <li>more elements</li>
</ul>

CSS:

CSS:

.selected:previous {
   color: red;
}

.selected:next {
   color: green;
}

That's possible?

那可能吗?

回答by sandeep

It's not possible with pure css. You can style next but not previous element.

纯 css 是不可能的。您可以为下一个元素设置样式,但不能为上一个元素设置样式。

But you can do a trick with css. Instead of give class selectedyou can give class to your previouselement. Like this:

但是你可以用css做一个技巧。您可以为之前的元素指定类,而不是选择类。像这样:

HTML

HTML

<ul>
 <li>zero</li>
 <li class="previous">one</li>
 <li>two</li>
 <li>three</li>
 <li>more elements</li>
</ul>

CSS

CSS

.previous{
   color: green;
}
.previous + li{
   color: red;
}
.previous + li + li{
    color:yellow;
}

Check this http://jsfiddle.net/S5kUM/2/

检查这个http://jsfiddle.net/S5kUM/2/

回答by Robert Smith

It's called sibling selector:

它被称为兄弟选择器:

.selected + li {
   color: red;
}

Fiddle here

在这里摆弄

However, there is no sibling selector for the previous element. ?

但是,前一个元素没有同级选择器。?

回答by Colin Kenney

This would have to be done with JavaScript.

这必须用 JavaScript 来完成。

If you are using jQuery, it can be done like this:

如果您使用的是 jQuery,则可以这样做:

$('.selected').prev().css('color', 'red');
$('.selected').next().css('color', 'green');

回答by captainpixel

You can use display: flex;and flex-direction: row-reverse;to reverse the list.

您可以使用display: flex;flex-direction: row-reverse;来反转列表。

http://codepen.io/bscherer/pen/XMgpbb

http://codepen.io/bscherer/pen/XMgpbb