LESS CSS - accessing classes further up the dom tree from within a nested class

依然范特西╮ 提交于 2019-11-28 04:34:22

问题


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 */
     }
}


来源:https://stackoverflow.com/questions/11519931/less-css-accessing-classes-further-up-the-dom-tree-from-within-a-nested-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!