在到达某个类之前将CSS应用于一组HTML标记[重复]

时间:2022-11-12 12:06:35

This question already has an answer here:

这个问题在这里已有答案:

I have a group of list tags inside of an unordered list such as:

我在无序列表中有一组列表标签,例如:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li class="active">4</li>
  <li>5</li>
  <li>6</li>
</ul>

Is there a way to target all of the list elements before or after the active class via CSS?

有没有办法通过CSS在活动类之前或之后定位所有列表元素?

2 个解决方案

#1


24  

You can target all of the sibling elements after with ~

你可以用〜来定位所有兄弟元素

li.active ~ li
{
    color: green;
}

JSFiddle

的jsfiddle


In CSS, you cannot target siblings prior to an element, so you would have to do something like this:

在CSS中,你不能在元素之前定位兄弟姐妹,所以你必须做这样的事情:

Give them all a rule:

给他们一个规则:

li
{
    color: orange;
}

Then overwrite the active one

然后覆盖活动的那个

li.active
{
    color: red;
}

Then overwrite the ones after

然后覆盖之后的那些

li.active ~ li
{
    color: green;
}

JSFiddle

的jsfiddle

#2


1  

Just to point it out, another way could be:

只是指出来,另一种方式可能是:

li:not(.active) {
  /* your css rules here */
}

This will select every li who doesn't have the class .active

这将选择每个没有类.active的li

#1


24  

You can target all of the sibling elements after with ~

你可以用〜来定位所有兄弟元素

li.active ~ li
{
    color: green;
}

JSFiddle

的jsfiddle


In CSS, you cannot target siblings prior to an element, so you would have to do something like this:

在CSS中,你不能在元素之前定位兄弟姐妹,所以你必须做这样的事情:

Give them all a rule:

给他们一个规则:

li
{
    color: orange;
}

Then overwrite the active one

然后覆盖活动的那个

li.active
{
    color: red;
}

Then overwrite the ones after

然后覆盖之后的那些

li.active ~ li
{
    color: green;
}

JSFiddle

的jsfiddle

#2


1  

Just to point it out, another way could be:

只是指出来,另一种方式可能是:

li:not(.active) {
  /* your css rules here */
}

This will select every li who doesn't have the class .active

这将选择每个没有类.active的li