Less Functions and Operations — Complete Guide
In this tutorial, you will learn about Less Functions and Operations. We cover key concepts, practical examples, and best practices to help you master this topic.
Less built-in functions include color manipulation, math operations, string handling, and Type Checking for dynamic stylesheet generation.
What You'll Learn
- Color functions (darken, lighten, fade, mix)
- Math operations and unit functions
- String functions
- Type checking functions
- List functions
- Custom function alternatives (mixins with return values)
Why It Matters
- Functions compute values programmatically
- Color functions create consistent palettes
- Math operations handle responsive calculations
- Type checking validates arguments
Real-World Use
- A palette generates from a single base color
- Fluid typography uses math operations
- A button color function creates hover states
- A theme validates color values
flowchart LR A[Less Functions] --> B[Color] A --> C[Math] A --> D[String] A --> E[Type Checking] B --> F[darken, lighten, fade, mix] C --> G[ceil, floor, round, percentage] D --> H[escape, e, % format] E --> I[isnumber, iscolor, isurl]
Functions in Less
Code Example: Color Functions
// Color manipulation
@primary: #0066CC;
.element-1 {
background: darken(@primary, 10%); // Darker by 10%
color: lighten(@primary, 60%); // Lighter by 60%
}
.element-2 {
background: saturate(@primary, 20%); // More saturated
color: desaturate(@primary, 30%); // Less saturated
}
.element-3 {
background: fade(@primary, 50%); // 50% transparent
color: mix(@primary, #fff, 80%); // Mix with white
}
.element-4 {
background: fadein(@primary, 10%); // Less transparent
color: fadeout(@primary, 20%); // More transparent
}
.element-5 {
background: spin(@primary, 30deg); // Shift hue +30
border-color: contrast(@primary, #333, #fff); // Auto contrast
}
// Color channel extraction
.element {
@hue: hue(@primary); // ~210 degrees
@sat: saturation(@primary); // 100%
@light: lightness(@primary); // 40%
@red: red(@primary); // 0
@green: green(@primary); // 102
@blue: blue(@primary); // 204
@alpha: alpha(@primary); // 1
}
// Creating a palette
.generate-palette(@color, @name) {
.bg-@{name} { background: @color; }
.bg-@{name}-light { background: lighten(@color, 30%); }
.bg-@{name}-dark { background: darken(@color, 15%); }
.text-@{name} { color: @color; }
.border-@{name} { border-color: @color; }
}
.generate-palette(#0066CC, 'primary');
.generate-palette(#28a745, 'success');
.generate-palette(#dc3545, 'danger');
Expected output: Less color functions include darken, lighten, saturate, desaturate, fade, mix, spin, and contrast. The contrast function automatically selects readable text color.
Code Example: Math Operations
// Math in Less is more permissive than modern Sass
// Less does not require math.div() - use standard operators
@base: 16px;
.element {
// Basic operations (safer in Less than Sass)
width: 100% / 3; // 33.33333%
padding: @base * 2; // 32px
margin: @base + 8px; // 24px
font-size: @base - 2px; // 14px
}
// Math functions
.element {
width: ceil(33.33%); // 34%
height: floor(33.33%); // 33%
opacity: round(0.555); // 1 (rounds to nearest integer)
z-index: abs(-100); // 100
min-width: min(100%, 800px); // Smaller of the two
max-width: max(400px, 50%); // Larger of the two
}
// Unit functions
@value: 16px;
.element {
// Remove units
@unitless: unit(@value); // 16
// Convert units
@converted: unit(@value, em); // 16em (just changes string)
// Check unit type
@is-px: ispixel(@value); // true
@is-em: isem(@value); // false
}
// Percentage
@ratio: 0.75;
.element {
width: percentage(@ratio); // 75%
}
// Min/max for responsive calculations
@min-size: 16px;
@max-size: 24px;
@min-vw: 320px;
@max-vw: 1200px;
// Fluid calculation (Less handles division differently)
.element {
// Manual clamp calculation
font-size: @min-size;
font-size: clamp(@min-size, @min-size + (@max-size - @min-size) * ((100vw - @min-vw) / (@max-vw - @min-vw)), @max-size);
}
Expected output: Less math uses standard operators (/ for division, * for multiplication, + and - for addition/subtraction). No special module import needed. Less handles unit conversions more leniently than Sass.
Code Example: String and Type Functions
// String functions
@url: 'https://example.com/image.jpg';
.element {
background: escape(@url);
// Output: background: https%3A%2F%2Fexample.com%2Fimage.jpg
content: e('Hello World');
// CSS escaping (removes quotes): content: Hello World;
content: %('Hello %s!', 'World');
// Format string: content: 'Hello World!';
}
// String with format for selectors
@name: 'primary';
@selector: ~'.btn-@{name}';
// The ~ creates an unquoted string (selector)
// Type checking
@value: 16px;
@color: #0066CC;
@string: 'hello';
@list: 10px, 20px, 30px;
.check-types() {
@if isnumber(@value) { } // true (px values are numbers)
@if iscolor(@color) { } // true
@if isstring(@string) { } // true
@if isurl(url('test')) { } // true
@if ispixel(@value) { } // true
@if isem(@value) { } // false
@if ispercentage(50%) { } // true
@if isruleset(@rules) { } // true for detached rulesets
}
// Usage in mixin guards
.mixin(@value) when (isnumber(@value)) {
width: @value * 1px;
}
.mixin(@value) when (isstring(@value)) {
content: @value;
}
Expected output: String functions handle URL escaping, format strings, and unquoted strings. Type checking functions (isnumber, iscolor, isstring, etc.) validate argument types for conditional compilation.
Code Example: List Functions
// List functions
@colors: #0066CC, #28a745, #dc3545, #ffc107;
// List length
@count: length(@colors); // 4
// Access by index (1-indexed)
@first: extract(@colors, 1); // #0066CC
@last: extract(@colors, 4); // #ffc107
// List iteration (via loops)
// Less does not have built-in @each like Sass
// Use "when" guards with recursion instead
.loop-colors(@index) when (@index > 0) {
.loop-colors(@index - 1);
@color: extract(@colors, @index);
.color-@{index} {
background: @color;
}
}
.loop-colors(length(@colors));
// Alternative: generate with mixin
.generate-utilities(@list, @prefix, @property, @index: 1) when (@index <= length(@list)) {
@value: extract(@list, @index);
.@{prefix}-@{index} {
@{property}: @value;
}
.generate-utilities(@list, @prefix, @property, @index + 1);
}
@spacings: 4px, 8px, 16px, 24px, 32px;
.generate-utilities(@spacings, 'mt', 'margin-top');
.generate-utilities(@spacings, 'mb', 'margin-bottom');
.generate-utilities(@spacings, 'pt', 'padding-top');
.generate-utilities(@spacings, 'pb', 'padding-bottom');
Expected output: Less list functions include length() and extract(). Less does not have built-in @each or @for loops. Recursive mixins with guards provide the equivalent functionality for iteration.
Common Mistakes
- Using Sass-style functions — Less function names differ from Sass. For example, fade() instead of rgba(), spin() instead of adjust-hue().
- Expecting @each or @for in Less — Less does not have these directives. Use recursive mixins with guards for iteration.
- String concatenation without format — Less uses ~ for unquoted strings and % for format strings, not simple interpolation.
- Math unit mismatch — Less is more lenient with units but can still produce unexpected results when mixing incompatible units.
- Forgetting contrast() is built-in — Less has a built-in contrast() function that selects black or white text based on background luminance.
- No custom function definition — Less does not have @function. Use mixins that set a variable as a return value pattern.
- Type checking in wrong context — Type functions work in guards and variable assignments but not as standalone property values.
Practice Questions
- What Less function creates a semi-transparent color? fade(@color, @percentage) reduces opacity.
- How do you round up a number in Less? ceil(@number) rounds up to the nearest integer.
- What does extract(@list, 2) return? The second item from the list (1-indexed).
- How do you iterate over a list in Less? Use a recursive mixin with a guard: .loop(@i) when (@i > 0) { .loop(@i - 1); @item: extract(@list, @i); }
FAQ
Mini Project
Create a comprehensive Less function library. Build: (1) a color palette generator using darken, lighten, and mix functions, (2) a fluid typography function using math and clamp, (3) a recursive mixin that generates spacing utility classes from a list, (4) a color validation mixin using type checking (iscolor, lightness), (5) a list-based button generator that creates variants from a color list, (6) a contrast utility using the built-in contrast() function. Compile and verify all functions produce correct output. Compare the syntax side by side with the equivalent Sass functions from earlier lessons.
What's Next
Continue with Lesson 24: Stylus Basics for an overview of the Stylus preprocessor.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro