将css样式应用于特定顺序的元素[复制]

时间:2022-02-15 11:15:39

This question already has an answer here:

这个问题已经有了答案:

So I have a situation, where I have a list of elements like these:

所以我有一种情况,我有一个这样的元素列表:

<li class="a">1</li>
<li class="a">2</li>
<li class="a">3</li>
<li class="b">4</li>
<li class="b">5</li>
<li class="a">6</li>
<li class="a">7</li>

Now what I want to achieve is to use CSS queries to apply red background to the first and last occurrence of a. So in the example above: 1, 3, 6, 7 will have the background color red.

现在我想要实现的是使用CSS查询将红色背景应用到第一个和最后一个出现的a中,所以在上面的例子中:1、3、6、7将会有背景色红色。

How can this be achieved using css? I have tried using css siblings queries but I can't find a way to determine when the switch from a -> b happens.

如何使用css实现这一点?我尝试过使用css兄弟姐妹查询,但是我找不到一种方法来确定从a -> b的转换发生的时间。

2 个解决方案

#1


0  

.a:nth-child(1) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(3) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(6) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(7) {
    background: red none repeat scroll 0 0;
}
<li class="a">1</li>
<li class="a">2</li>
<li class="a">3</li>
<li class="b">4</li>
<li class="b">5</li>
<li class="a">6</li>
<li class="a">7</li>

you just need to change no which one you want to be make red background

你只需要改变你想成为红色背景的人。

.a:nth-child(no will come here ) {
    background: red none repeat scroll 0 0;
}

#2


0  

As i understand from your question you need to apply background color red on every occurance first and last child elements. for this please refer the following css code.

我从你的问题中了解到,你需要在每一个出现的第一个和最后一个子元素上应用背景色。为此,请参考下面的css代码。

.a:nth-child(2n+1), .a:nth-last-child(2) {
background: red;}

#1


0  

.a:nth-child(1) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(3) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(6) {
    background: red none repeat scroll 0 0;
}
.a:nth-child(7) {
    background: red none repeat scroll 0 0;
}
<li class="a">1</li>
<li class="a">2</li>
<li class="a">3</li>
<li class="b">4</li>
<li class="b">5</li>
<li class="a">6</li>
<li class="a">7</li>

you just need to change no which one you want to be make red background

你只需要改变你想成为红色背景的人。

.a:nth-child(no will come here ) {
    background: red none repeat scroll 0 0;
}

#2


0  

As i understand from your question you need to apply background color red on every occurance first and last child elements. for this please refer the following css code.

我从你的问题中了解到,你需要在每一个出现的第一个和最后一个子元素上应用背景色。为此,请参考下面的css代码。

.a:nth-child(2n+1), .a:nth-last-child(2) {
background: red;}