Getting Started with Less

File Structure and Importing

File Structure

A Less file is simply this: .less.

The major difference between .less files and .css files is how you do your includes.

With CSS you previously could do something like this:


/* Your CSS probably roughly looks like this */

@import 'slices/reset.css';
@import 'slices/fonts.css';

h1 {
    color: #777;
    font-weight: 700;
    font-size: 25px;
}

.my-super-cool-box {
    display: block;
    background: #ff7c7c;
    border: solid 5px red;
}

This is really awesome in CSS for organizational purposes, but it actually is very bad practice. Here's why:

/* Web Request 1: (this CSS file) */


/* Web Request 2 */
@import 'slices/reset.css';

/* Web Request 3 */
@import 'slices/fonts.css';



h1 {
    color: #777;
    font-weight: 700;
    font-size: 25px;
}

.my-super-cool-box {
    display: block;
    background: #ff7c7c;
    border: solid 5px red;
}

That's absolutely brutal for load times to force the user to make the separate web request even though you received the organizational benefit.

So, if you've been writing CSS and HTML, you have probably been taught to avoid that if you can.

With Less though, this is okay because the `.less files will compile down. Here's what it would look like:

@import 'slices/reset'; 
@import 'slices/fonts'; 
@import 'slices/custom-styles'; 

"Imports" Are Now Awesome

Since less will "compile" all those files into a single file, you can separate and organize your code as much as you'd like. It's encouraged!

So, went you setup your .less files you'll want to structure it something like this:

slices/
    reset.less
    fonts.less
    base.less
    headings.less
    forms.less
    ...
    ...
    ...
style.less

Where your style.less looks like this:

@import 'slices/reset'; 
@import 'slices/fonts'; 
@import 'slices/base'; 
@import 'slices/headings'; 
@import 'slices/forms'; 
...
...
...

Importing can also be .css files or if you prefer you can write .less. For example:

@import 'slices/reset.css'; // Import a CSS file
@import 'slices/fonts.less'; // Preference thing 1
@import 'slices/base.less'; // Preference thing 1
@import 'slices/headings'; // Preference thing 2 
@import 'slices/forms'; // Preference thing 2
...
...
...

"Slices" Folder Name

This is my personal preference. The more industry standard however is to call this folder one of these:

  • modules/
  • includes/
  • partials/

For your projects, honestly just name it whatever you want. If you're working with a team, maybe you all can agree on something together or just try to use an industry standard.