Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

nested

less

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?

like image 688
albion60 Avatar asked Jul 17 '12 09:07

albion60


2 Answers

Yes! (an update)

When I tested this here, it worked!

    .container { 
        .logo { 
            background:url(/images/logo.gif);
            .svg & {
                background:url(/images/svg-logo.svg);
            } 
        } 
    }
like image 64
ScottS Avatar answered Nov 10 '22 03:11

ScottS


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 */
     }
}
like image 32
Christoph Avatar answered Nov 10 '22 03:11

Christoph