LESS CSS - accessing classes further up the dom tr

2020-02-12 09:04发布

问题:

I want to be able to access classes further up the dom tree from within a nested class using LESS CSS, see example:

HTML:

<html class="svg">
 <body>
  <div class="content">
    <div class="container">
      <div class="logo"></div>
    </div>
 </body>
</html>

LESS:

.container {
  .logo {
      background:url(/images/ws-logo.gif);
  }
}

I want to target the .svg class on the html tag from within the .logo nested rule, to keep things tidy instead of writing another rule like this:

.svg { 
  .container {
    .logo {
        background:url(/images/logo.svg);
    }
  }
}

So, ideally something like this:

 .container {
    .logo {
        background:url(/images/logo.gif);

        (some-symbol).svg {
           background:url(/images/svg-logo.svg);
        }
    }
 }

I'm using modernizr to detect svg support.

Anyone know if this is possible? Or have any recommendations?

回答1:

Yes! (an update)

When I tested this here, it worked!

    .container { 
        .logo { 
            background:url(/images/logo.gif);
            .svg & {
                background:url(/images/svg-logo.svg);
            } 
        } 
    }


回答2:

This is not possible because you can't "step back" in the path to add another class to a parent. Instead, just write another rule:

.svg .container .logo,
/* or perhaps even simpler, however be aware of rule specificity*/
.svg .logo{
        background:url(/images/logo.svg);
}

It's not much of a deal, is it?

For the sake of completeness: You can reference to the actual element via the &-symbol. THis makes sense if you want to target pseudo-classes/elements or additional classes of the current element:

.container {
     .logo {
         /* styles for ".container .logo" */
     }
     &:hover .logo{
         /* styles for ".container .logo"
            The hover however is bound to the .container element
            equals the following selector: .container:hover .logo */
     }
}


标签: css nested less