What is bubbling in Less?
Overview
LESS is a CSS Preprocessor with built-in features that makes our work easier. LESS code is written and is later compiled to a CSS file by running some simple codes.
Bubbling in LESS
Classes and variables in LESS can be nested to improve our CSS codes. This way, directives can also be nested.
Note: When we layer directives like media and keyframe in the same way as we organize selectors, this is referred to as the Bubbling process. The directive’s related parts won’t change within its rule set even if we put it on top of them.
Code example
Suppose we have a class, myText. And we want to give this class a blue color on a screen that has a minimum width of 600px and red on a screen with a minimum width of 769px and default color of black. We can write the code in our less file as below:
.myText{@media screen{color: #000;@media (min-width: 600px){color: #0000ff;}@media (min-width: 769px){color: #ff0000;}}}
Code explanation
- Line 1: We create a
.mTextclass. - Line 2: We create a directive
@media screenwhich has a black color. - Line 4: We have a nested directive for a minimum width of
600pxand with a blue color. - Line 7: We have another nested directive for a minimum width of
769pxwith a red color.
The next step is to compile the less file into the CSS file.
lessc nameOfFile.less nameOfFile.css
After running the text above to compile the less file, our CSS file will look like this:
@media screen{.myText{color: #000;}}@media screen and (min-width: 600px){.myText{color: #0000ff;}}@media screen and (min-width: 769px){.myText{color: #ff0000;}}
Live code
Run the code given below by following the given instructions:
- Press the “Run” button to connect to the terminal.
- Type the following command:
lessc nameOfFile.less nameOfFile.css - To see the generated output file use the command:
cat nameOfFile.css
.myText{
@media screen{
color: #000;
@media (min-width: 600px){
color: #0000ff;
}
@media (min-width: 769px){
color: #ff0000;
}
}
}