shaft shaft - 2 months ago 16
Sass (Sass) Question

css mixins using an external framework

How can you use css mixins based on an existing library? Example: Consider you want to create a new css class based on the bootstrap

btn btn-success
classes. It might look like:

.disabled-button {
@mixin .btn;
@mixin .btn-success;
@mixin .disabled;
color:red;
}


Less/Sass are capable of doing such kind of things when you define the classes
btn
or
btn-success
yourself, but how do you deal with it when it comes from bootstrap (or another css framework) ?

Answer

If you can add LESS compilation into your workflow, you can achieve this easily with its @import (reference) and :extend(x all). Without needing to learn anything more about LESS, you'd do

@import (reference) "bootstrap.less"; // this file is included with bootstrap. `(reference)` means it will only pull in the styles you ask it for, so you could continue using this even if you switch to another framework and don't want to include all of bootstrap
.disabled-button:extend(.button all, .button-success all, .disabled all) {} // pulls in the `.button` styles, `.button-success` styles, and `.disabled` styles
.disabled-button {color:red} // adds on your styles

Explanation of LESS's :extend(all) and relevant documentation links are in this answer

Since CSS is valid LESS, you wouldn't have to make any other changes to your stylesheet. Okay, so how do you add LESS compilation to your workflow? The simplest solution is described in LESS's "Command Line Useage" documentation, which boils down to installing less (once)

$ npm install less -g

and then running lessc, the less compiler

$ lessc my-styles.less my-compiled-styles.css
Comments