Variables inside selectors in LESS
Variables can also be used inside selectors. However, to do this, you need to use a slightly different syntax for inserting a variable: after @
, the variable name must be taken in curly brackets. Let's look at some examples. Let's say we have the following variable:
@var: div;
Let's insert this variable into the selector. Let's look at different situations.
Example
Let's insert our variable as a selector:
@{var} {
font-size: 20px;
}
Compilation result:
div {
font-size: 20px;
}
Example
Now let our variable contain part of the selector:
main @{var} {
font-size: 20px;
}
Compilation result:
main div {
font-size: 20px;
}
Example
Now let's say that our variable contains not the tag name, but its id
. Let's add a hash before the variable name:
#@{var} {
font-size: 20px;
}
Compilation result:
#div {
font-size: 20px;
}
Example
Now let's say that our variable contains not the tag name, but its class. Let's add a dot before the variable name:
.@{var} {
font-size: 20px;
}
Compilation result:
.div {
font-size: 20px;
}
Practical tasks
Tell me what the result of compiling the following code will be:
@var: ul;
@{var} {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: ul;
div @{var} {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: ul;
div @{var} {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: ul;
@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: list;
.@{var} {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: list;
#@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: list;
.@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: list;
ul.@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: list;
ul.@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: .block;
ul@{var} {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: .block;
ul@{var} li {
font-size: 20px;
}
Tell me what the result of compiling the following code will be:
@var: a;
@{var}:hover {
text-decoration: none;
}
Tell me what the result of compiling the following code will be:
@var1: div;
@var2: a;
@{var1} @{var2}:hover {
text-decoration: none;
}
Tell me what the result of compiling the following code will be:
@var1: block1;
@var2: block2;
.@{var1}.@{var2} {
font-size: 20px;
}