3

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?

A. Kolbo
  • 81
  • 9
  • 1
    CSS-in-js allows you to use the spread operator to do things like this. – giraffesyo Oct 08 '18 at 04:14
  • You can't do it in pure CSS, but using Less would work just like that. I'll answer showing you how to do so with Less. – Jack Bashford Oct 08 '18 at 04:20
  • 1
    Possible duplicate of [Can a CSS class inherit one or more other classes?](https://stackoverflow.com/questions/1065435/can-a-css-class-inherit-one-or-more-other-classes) – DanOPT Oct 08 '18 at 04:45
  • It's possible in CSS. Less will be compiled to CSS, too. – DanOPT Oct 10 '18 at 02:26

2 Answers2

2

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)

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
2

This is the pure CSS way, but syntax is slightly different and you don't need the first line:

.author {} /* 1st line is not required*/

.author, .class1 {
  width: 100px;
}
.author, .class2 {
  height: 100px;
  background-color: black;
}
<div class="author"><div>

More Information here: Can a CSS class inherit one or more other classes?

DanOPT
  • 128
  • 2
  • 13