Variable Operations (Arithmetic, String Concatenation) in LESS

Variable Operations (Arithmetic, String Concatenation) in LESS

In the LESS preprocessor, variables serve as the cornerstone for building complex styling systems, while their computational capabilities empower developers to perform logical calculations and dynamic generation during the initial design phase. LESS supports various arithmetic operators (addition, subtraction, multiplication, division) as well as string concatenation operations. These features allow CSS variables to be used flexibly, much like variables in programming languages. Mastering these fundamental operation rules is a crucial step towards deeply understanding the core concepts of LESS.
LESS arithmetic operations follow standard mathematical logic, supporting mixed calculations between integers, decimals, and percentage values. When performing operations on two or more variables, the result is automatically assigned to the target variable or the expression itself.

When defining and using variables, they must start with a dollar sign $. For example, we can define basic color variables:

@primaryColor: #3498db;
@secondaryColor: #2ecc71;
@borderWidth: 2px;

Based on these variables, we can easily perform addition, subtraction, multiplication, and division operations. LESS automatically handles parentheses precedence, but explicitly using parentheses in complex expressions ensures clear logic:

// Calculate the new border width (original width + 4px)
@newBorderWidth: @borderWidth + 4px;

// Calculate a mixed color value (requires other functions for actual implementation; here only demonstrating variable numerical operation logic)
@mixedValue: (@primaryColor + @secondaryColor) / 2; 

It is important to note that while LESS supports simple arithmetic addition, subtraction, multiplication, and division of numbers, direct arithmetic operations on color values (such as adding RGB components) usually require conversion using rgb() or rgba() functions. Pure hexadecimal color mathematical operations often lack practical meaning in CSS.

String Concatenation and Connection Operations

In addition to numerical operations, LESS also provides powerful string concatenation capabilities. This is crucial for dynamically generating class names, media query conditions, or constructing complex CSS text content. LESS uses the + symbol to implement string concatenation, consistent with JavaScript behavior.

When performing string concatenation, if a variable contains spaces or other special characters, it must be wrapped in single or double quotes; otherwise, LESS will parse them as independent tokens:

@prefix: "my-";
@suffix: "theme";

// Incorrect syntax (parsed as two independent tokens)
@className: @prefix my- @suffix; 

// Correct syntax (concatenated into a complete string)
@className: @prefix + @suffix; 

After running the above code, the value of @className will become "my-theme". This mechanism allows us to perform conditional judgments or dynamic combinations when writing CSS, such as automatically adding a prefix based on the theme mode:

@if (getComputedStyle(document.body).theme == "dark") {
    @darkModePrefix: "dark-";
} else {
    @darkModePrefix: "light-";
}

@buttonName: @darkModePrefix + "btn-primary";

Assignment and Application of Operation Results

The ultimate purpose of variable operations in LESS is typically to generate new style values. In LESS, we can use the calculated result directly within a rule block or assign it to a new variable for reuse.

Assume we need to dynamically adjust padding based on container size:

@containerSize: 800px;
@paddingUnit: 1rem;

// Calculate total padding (half of width plus fixed unit)
@totalPadding: (@containerSize / 2) + @paddingUnit;

.container {
    padding: @totalPadding;
}

The compiled CSS will generate the following content:

.container {
    padding: 401px; /* Assuming 1rem = 40px */
}

Additionally, string concatenation is very practical when constructing media query conditions. Although standard CSS does not support variables directly embedded in condition judgments within @media queries, through LESS's computational capabilities, we can generate pseudo-classes or helper classes that meet specific conditions:

@screenWidth: 768px;
@breakpointName: "md";

@media (min-width: @screenWidth) {
    .class-{@breakpointName} {
        display: block;
    }
}

Best Practices and Precautions

When using LESS variable operations, developers should follow the following best practices to ensure code maintainability and performance:

  • Avoid Over-nesting: While it is possible to nest operations at multiple levels, it is recommended to extract complex calculation logic into separate variables to keep rule blocks concise.
  • Type Checking: Ensure operand types are consistent or understand LESS's implicit conversion rules before performing mixed operations. For example, directly adding a number and a string may lead to unexpected results.
  • Performance Considerations: In large-scale projects, frequent string concatenation may increase compilation time. For high-frequency dynamic logic, consider using CSS variables (Custom Properties) as an alternative solution, which are processed by the browser at runtime rather than the preprocessor.

By mastering addition, subtraction, multiplication, division, and string concatenation of variables, developers can more flexibly address dynamic design requirements, improve development efficiency, while maintaining clear and standardized code structure.