Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define variables in one LESS file

Tags:

css

less

I've just started using LESS to simplify my CSS stuff. I want to be able to define the colours in one file, so I can have several colour schemes that I can switch between just by changing which file is being referenced.

I tried something like this:

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

But I get "variable not defined" errors in the styles.less file.

I can "fix" this by using import "/css/colours.less" at the start of styles.less, but I have to do this for every single LESS file, and it makes it much, much harder to change what file is being used.

Is there any way to define variables in one file and use them in another? Or any way to auto-import the colours.less file at the start of the other files?

like image 702
Niet the Dark Absol Avatar asked Apr 19 '13 03:04

Niet the Dark Absol


1 Answers

You should be compiling your .less files into a single .css file and including it once on every page (i.e. styles.less compiled to styles.css). That way the browser doesn't have the overhead of recompiling the CSS every page load. Also the .css file can be cached.

Instead of adding:

<link href="/css/colours.less" />
<link href="/css/styles.less" />
<link href="/css/forms.less" />
<link href="/css/widgets.less" />
...etc...

It should be:

<link href="/css/styles.css" />

And in styles.less you should have:

@import 'colours';
@import 'forms';
@import 'widgets';
...etc...

Otherwise, if you want to reuse colours.less in multiple .less stylesheets, you'll need to @import them in each stylesheet.


For development purposes, I recommend using a single, primary .less file that contains only variable declarations and @import statements. That way it's easy to find where additional scripts are added. LESS makes it very easy to add or remove stylesheets to keep the code organized.

For example, style.less might look something like:

// import statements
@import 'core';
@import 'mixins';
@import 'lists';
@import 'buttons';

@import 'forms/form';
@import 'forms/search';
@import 'forms/contact-us';

@import 'modules/module';
@import 'modules/archive';
@import 'modules/events';

// variables
@image-path: '/assets/images/';

@font: Helvetica, Arial, sans-serif;

@black: #000;
@dark-grey: #333;
@grey: #888;
@light-grey: #CCC;
@white: #FFF;
@red: #F00;

This structure makes it easy to add a new stylesheet, such as when adding a new module:

...
@import 'modules/events';
@import 'modules/foo'; //add another module
...

It also makes it very easy to remove styles if they're no longer being used. If the foo module was to be removed, it's easy to remove all the foo styles simply by removing the @import 'modules/foo'; statement.

like image 117
zzzzBov Avatar answered Sep 18 '22 13:09

zzzzBov