Search code examples
csslessconditional-statementsstylesheet

Less conditional style inclusion


I'm kinda new to LESS, so I'm not sure if that's possible and how. So my idea is this :

I have a main-stylesheet.less and a dozen smaller stylesheets each of which contains several versions of styling for a particular element i.e. header.less, footer.less, main-nav.less etc. So in header.less every variant of styling is linked to a condition and when you include this LESS file in the main-stylesheet.less via this condition, just that particular chunk of code is compiled and not the other ones that are linked to other conditions.

I hope I've been thorough enough for you to best understand me.

Is this possible and how ?


Solution

  • Keeping it Generic

    By using conditional mixins, the code in main-stylesheet.less stays generic, with only the variables changing to control what is actually compiled.

    Example header.less

    .header() when (@header = 1) {
       #header {
         your: properties;
         for: header1;
       }
    }
    
    .header() when (@header = 2) {
       #header {
         your: properties;
         for: header2;
       }
    }
    

    This could continue on, and similar code would be in the other footer.less files, etc.

    Example main-sytlesheet.less

    @import header.less;
    @import main-nav.less;
    @import footer.less;
    
    /* set your variables for your conditional mixins */
    @header: 1;
    @main-nav: 3;
    @footer: 3;
    
    /* call the mixins */
    .header();
    .main-nav();
    .footer();
    

    The global variables you set will only choose the .header() mixin to generate the #header, etc. that @header variable is set to.