Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Operations and units

Less can calculate right inside your styles: +, -, * and / work with numbers, units and colours. This way sizes are derived from one base value: change the grid step and all spacing is recalculated.

Arithmetic

Create a base gap and derive the others from it in styles/main.less:

// styles/main.less
@gap: 16px;
 
.card {
  padding: @gap;
  margin-bottom: @gap * 2;
  border-radius: @gap - 12;
}
.card {
  padding: 16px;
  margin-bottom: 32px;
  border-radius: 4px;
}

A number without a unit (2, 12) takes the unit of the other value: @gap - 12 gives 4px.

Units

Less converts compatible units itself, and the result gets the unit of the first value. With incompatible units it does not complain and also takes the first one:

// styles/main.less
.ruler {
  width: 2cm + 5mm;
  height: 4px + 2em;
}
.ruler {
  width: 2.5cm;
  height: 6px;
}

2cm + 5mm correctly gave 2.5cm, but 4px + 2em gave a meaningless 6px: Less does not know how many pixels an em is. For mixed units use CSS calc(), which the browser calculates.

Division only in parentheses

In CSS the slash is an ordinary separator (font: 14px/1.5, grid-row: 1 / 3). That is why in Less 4 division happens only inside parentheses:

// styles/main.less
@gap: 16px;
 
.card {
  padding: (@gap / 2);
  grid-row: 1 / 3;
}
.card {
  padding: 8px;
  grid-row: 1 / 3;
}

Inside the parentheses Less divided, and 1 / 3 was left as it is. The other operations work without parentheses. In Sass division is written with the math.div() function.

Math functions

FunctionWhat it doesExampleResult
percentage()Turns a number into a percentagepercentage(0.25)25%
round()Rounds, the second argument is decimal placesround(33.333%, 1)33.3%
ceil(), floor()Round up and downfloor(4.8px)4px
unit()Changes or removes the unitunit(1.5, rem)1.5rem
min(), max()The smaller and the larger valuemax(8px, 12px)12px

An example: a grid column width and a font size in rem from pixels:

// styles/main.less
@columns: 12;
 
.col-4 {
  width: round(percentage((4 / @columns)), 2);
}
 
.lead {
  font-size: unit((20 / 16), rem);
}
.col-4 {
  width: 33.33%;
}
.lead {
  font-size: 1.25rem;
}
<style>
  .col-4 {
    width: 33.33%;
  }
  .lead {
    font-size: 1.25rem;
  }
</style>
 
<div class="col-4" style="background: #dbeafe">One third of the width</div>
<p class="lead">Large lead text</p>

Common mistake

Division without parentheses is not performed — Less 4 silently leaves the expression as it is:

// styles/main.less
@gap: 16px;
 
.card {
  padding: @gap / 2;
}
.card {
  padding: 16px / 2;
}

The browser does not understand 16px / 2 in padding and drops the whole declaration. Write (@gap / 2). Older projects written for Less 3 are sometimes built with the --math=always flag, which brings back the old behaviour.

Thanks for reading!

Donate to the site — we work hard for you.