Less CSS - SPLessons

Less Import Directives

Home > Lesson > Chapter 7
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Less Import Directives

Less Import Directives

shape Introduction

This chapter explains about Less Import Directives and different file extensions for Importing.

shape Description

The files in a code can be imported using the @import directive in Less. One can maintain the code structure easily by using the Less import directive and spread the code across different files. In the case of CSS, the @import statement must precede all other rules, whereas, in Less @import statement can be used anywhere in the code.

shape Syntax

@import “file_name.less”

File Extensions for less importing

shape Description

Depending on the file extension, the files are treated differently by the @import statement. [c]@import "foo";          // foo.less is imported @import "foo.less";      // foo.less is imported @import "foo.php";    // foo.php imported as a less file @import "foo.css";    // statement left in place, as it is[/c]

shape Example

Below example explains the use of import directive in less.

shape Conceptual figure

The below conceptual diagram represents the overall view about the example like creating .html and .less files in node js folder and compiling .less to .css

shape Step 1

Create a HTML file in the Nodejs folder as shown below. import_dir.html [c] <head> <title>Import Directives</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <h2>Welcome to SPLessons</h2>    <p class="myline">small example on Less Import directives</p> </body> </html> [/c]

shape Step 2

Now, create two less files in the same Nodejs folder as shown below. import_dir.less [c] .myline { font-size: 20px; } [/c] style.less [c] @import "C:\Users\Samuel\nodejs\import_dir.less"; .myline { color: #5858FA; } [/c]

shape Step 3

Compile the above code in the command prompt by using the command. [c]lessc style.less style.css[/c]

shape Step 4

By compiling the above .less file, it automatically generates .css file as shown below. style.css [c] .myline { font-size: 20px; } .myline { color: #5858FA; } [/c]

shape Result

After making all the required changes, you need to run the html file in a browser to get the following output.

Summary

shape Key Points

  • The code structure can be maintained easily using the @import directive.
  • Using the file extension, the @import statement defines the file in less.

shape Programming Tips

  • Make sure that @import statement is defined before importing a file.
  • Create both .html and .less files in the node js folder.
  • Make sure to give the correct path for importing a file into the code.