Search code examples
htmlcsssassgulp

Combining Classes in CSS and Not HTML


Is there a tool out there that allows you to combine CSS classes? It seems handy to combine them in something like Tailwind css, but is there a way to "add them up" in the css? Sass has the @extend which is similar to what I'm thinking. But is there something out there that looks like this:

HTML:

<div class="author"></div>

CSS:

.card {with: 100px; height: 100px;}
.green (background-color: green}

.author { .card + .green }

or maybe

.author = .card.green

Then with more classes, it'd end up something like:

.author, 
.staff, 
.jockey = .card.green.padding-large.centered.motif-top

Does this exist?


Solution

  • You can do so with the help of Less.css. Just add this <script> tag to your HTML file:

    <script src="//cdnjs.cloudflare.com/ajax/libs/less.js/3.7.1/less.min.js" ></script>
    

    And add a <link> to an external stylesheet like this (this is not needed, but Less is less buggy if written in an external file .less rather than inside <style> tags in HTML):

    <link rel="stylesheet/less" type="text/css" href="styles.less" />
    

    Now, this example you provided:

    .card {width: 100px; height: 100px;}
    .green (background-color: green}
    
    .author { .card + .green }
    

    Can be written in Less as:

    .card {
        width: 100px;
        height: 100px;
    }
    
    .green {
        background-color: green;
    }
    
    .author {
        .card();
        .green();
    }
    

    And the second example of:

    .author, 
    .staff, 
    .jockey = .card.green.padding-large.centered.motif-top
    

    Is written in Less like:

    .author, .staff, .jockey {
        .card();
        .green();
        .padding-large();
        .centered();
        .motif-top();
    }
    

    Hopefully this helped you, and go to the official website to learn more about Less CSS (Learner Style Sheets)