Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS to a group of HTML tags before reaching a certain class [duplicate]

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?

like image 889
uneducatedguy Avatar asked Feb 12 '15 23:02

uneducatedguy


People also ask

How do I apply multiple CSS classes in HTML?

To specify multiple classes, separate the class names with a space, e.g. <span class="left important">. This allows you to combine several CSS classes for one HTML element.

How do you duplicate elements in CSS?

Short answer no, in css you can't create content or display it multiple times. Usually this repeated content is taken care of via server side technologies (PHP, JSP, ASPX) etc. If your site is static content (no server side processing) then your best bet is just copy and past.

How do I apply multiple elements in CSS?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

How do I inherit a class in CSS?

The inherit keyword specifies that a property should inherit its value from its parent element. The inherit keyword can be used for any CSS property, and on any HTML element.


1 Answers

You can target all of the sibling elements after with ~

li.active ~ li
{
    color: green;
}

JSFiddle


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

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

like image 90
Liftoff Avatar answered Nov 10 '22 05:11

Liftoff