Less is a dynamic stylesheet language that can be compiled to standard CSS code. Like SCSS, it extends the syntax of CSS with features such as variables, nesting, and mixins. This can make writing and managing CSS styles easier and more efficient.
Here’s an example of a simple Less rule that sets the font size and color of all h1
elements in a web page:
@base-font-size: 24px;
@base-color: #333333;
h1 {
font-size: @base-font-size;
color: @base-color;
}
In this example, we define two variables using the @ syntax: @base-font-size and @base-color . These variables are then used in the font-size and color declarations for the h1 element.
Less also supports nesting, which allows us to write more readable and maintainable CSS code by organizing related styles together. Here’s an example of how we might use nesting to define styles for a navigation menu:
nav {
ul {
list-style: none;
margin: 0;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: @base-color;
text-decoration: none;
&:hover {
text-decoration: underline;
}
}
}
In this example, we use nesting to define styles for the ul, li, and a elements inside the nav element. The & syntax is used to refer to the parent selector ( a:hover in this case).
Like SCSS, Less files are typically compiled to standard CSS code using a build tool or command line tool. This allows the browser to interpret the CSS code as normal.