Limitations of Plain CSS
CSS lacks programming constructs like variables, functions, and scoping. This leads to:
- High redundancy due to repetitive values (e.g., colors, spacing)
- Difficulty in maintenance and code reuse
- Limited arithmetic or dynamic capabilities
- Steep learning curve for non-specialists trying to write scalable stylesheets
What Is Less?
Less (Leaner Style Sheets) is a CSS preprocessor that extends standard CSS with features from programming languages. It retains all native CSS syntax while adding:
- Variables for reusable values
- Mixins for encapsulating style patterns
- Nested rules for clearer structure
- Mathematical operations
- Functions and conditionals (in advanced usage)
Other popular preprocessors include Sass and Stylus. Less compiles into standard CSS that browsers can interpret.
Setting Up Less
While modern editors like VS Code can compile Less via extensions (e.g., Easy LESS), global installation requires Node.js:
# Install globally via npm
npm install -g less
# Verify installation
lessc -v
Core Features
Varaibles
Define reusable values with @ prefix:
@primary-color: #ff69b4;
@base-font-size: 14px;
body {
color: @primary-color;
font-size: @base-font-size;
}
Naming rules:
- Must start with
@ - Cannot begin with a number
- No special characters (except hyphens/underscores)
- Case-sensitive (
@color≠@Color)
Compilation
Less files (.less) must be compiled to .css for browser use. With the Easy LESS plugin in VS Code, saving a .less file automatically generates a corresponding .css file.
Example HTML link:
<link rel="stylesheet" href="styles.css">
Nesting
Write hierarchical selectors more intuitively:
.header {
width: 200px;
a {
color: red;
&:hover {
color: blue;
}
}
}
.nav {
.logo {
color: green;
}
&::before {
content: "";
}
}
The & symbol references the parent selector, essential for pseudo-classes (:hover) and pseudo-elements (::before).
Operations
Perform arithmetic on numbers, colors, and variables:
@border-width: 5px + 5; // → 10px
@font-scale: 50px;
div {
width: 200px - 50; // → 150px
height: (200px + 50px) * 2; // → 500px
border: @border-width solid red;
background-color: #666 - #222; // → #444
}
img {
width: (82rem / @font-scale); // Parentheses required for division
}
Rules for operations:
- Always include spaces around operators:
5px + 10, not5px+10 - If units differ, result uses the left operand’s unit:
10px + 2em→12px - If only one value has a unit, result adopts that unit:
10 + 5px→15px