Importing files
It is convenient to keep a site's styles in several files: variables in one, buttons in another, cards in a third. The @import directive connects one Less file to another, and compilation produces one CSS file. In parentheses after @import you can give options that change how the import behaves.
An ordinary import
Create a file with variables and a component file:
// styles/variables.less
@primary: #2563eb;
@radius: 8px;// styles/components/buttons.less
.btn {
color: white;
background: @primary;
border-radius: @radius;
}The main file only connects the others. The .less extension can be left out:
// styles/main.less
@import "variables";
@import "components/buttons";.btn {
color: white;
background: #2563eb;
border-radius: 8px;
}Only main.less is compiled. All imported files see each other's variables and mixins — unlike @use in Sass, where every module has its own scope.
reference — use, but do not output
The (reference) option imports a file as a reference: its rules do not reach the CSS until you use them as a mixin yourself. This is how you take only what you need from a big library:
// styles/library.less
.btn {
padding: 8px 16px;
border-radius: 8px;
}
.card {
padding: 16px;
border: 1px solid #e5e7eb;
}// styles/main.less
@import (reference) "library";
.save-button {
.btn();
background: #16a34a;
}.save-button {
padding: 8px 16px;
border-radius: 8px;
background: #16a34a;
}The .btn and .card rules did not reach the CSS, and the declarations of .btn ended up in .save-button.
inline — insert as is
Less keeps an ordinary @import "file.css" as a CSS import. The (inline) option inserts the file's content straight into the result, without parsing it:
/* styles/vendor/reset.css */
* {
box-sizing: border-box;
}// styles/main.less
@import (inline) "vendor/reset.css";
.card {
padding: 16px;
}/* styles/vendor/reset.css */
* {
box-sizing: border-box;
}
.card {
padding: 16px;
}Other options
| Option | What it does |
|---|---|
(once) | Imports the file once, even if there are several imports. This is the default |
(multiple) | Imports the file as many times as there are imports |
(optional) | Does not fail if the file is missing |
(css) | Keeps the @import in the CSS whatever the extension |
(less) | Parses the file as Less even if its extension is .css |
Options can be combined with a comma: @import (reference, optional) "theme";.
Common mistake
Importing a file with the .css extension without options does not insert its content:
// styles/main.less
@import "vendor/reset.css";
.card {
padding: 16px;
}@import "vendor/reset.css";
.card {
padding: 16px;
}The @import line stayed in the CSS, and the browser will make a separate request for vendor/reset.css — relative to the css/ folder, where the file is not. To bundle everything into one file, write @import (inline) "vendor/reset.css"; or @import (less) "vendor/reset.css";.