2
votes

I am working with a codebase with multiple styles (coming from a redesign). I would like to be able to declare class="v1" or class="v2" on elements, to determine which style to use.

Importantly, some pages may contain elements with both styles, in which case the style applied should be whatever versioned parent is closest. For instance, if the body is v1, but the div is v2, then any styles inside that should be v2.

In SCSS, I can do something like this:

.v1 {
  p {
    // stuff for version 1 of the styles
  }
}

.v2 {
  p {
    // stuff for version 2 of the css
  }
}

Which sort of gets me there, but v2 will always overwrite v1 because it is lower in the CSS.

For instance, the following should be red, then blue, then red, then blue. However, it is red, then blue, then blue, then blue.

<html>
  <head>
  <style type="text/css">
    .v1 span {
      color: red;
    }
    .v2 span {
      color: blue;
    }
  </style>
  </head>
  <body class="v1">
    <span>Outside</span>
    <div class="v2">
      <span>Div 1</span>
      <div class="v1">
        <span>Div 2</span>
        <div class="v2">
          <span>Div 3</span>
        </div>
      </div>
    </div>
  </body>
</html>

What is a good way to do this?

1

1 Answers

3
votes

Edit

Per the OP's comment, this answer only addresses the OP's specific test case, and does not fully resolve the issue.

Have a look at CSS Child Selectors

What you had before was telling the page to take everything inside the v1 class that was a span and apply the red color to it. The spans inside the child divs were all inside the parent div that had a class of v1. Using the child selector, you are specifically telling it to look for a child element of a span inside a specific class.

The following seems to work:

.v1 > span {
  color: red;
}
.v2 > span {
  color: blue;
}

You can check this example working here JsFiddle