LESS (Leaner Style Sheets) is a simple CSS pre-processor that facilitates the creation of manageable, customizable, and reusable style sheets for websites. It is a dynamic style sheet language that enhances the working power of CSS. LESS supports cross-browser compatibility. CSS pre-processor is a scripting language that improves CSS and gets compiled into regular CSS syntax so that it can be used by the web browser. It is also a backward-compatible language extension for CSS that provides functionalities like variables, functions, mixins, and operations that enable us to build dynamic CSS.
CSS guards are applied to CSS selectors, which are syntactic sugar for declaring the mixin and then calling it immediately. You can also achieve an if type statement by combining this with the & feature, allowing you to group multiple guards.
Syntax:
@my-option:mixin; .my-optional-style() when (@my-option=mixin) { //property values }
Example 1: This example, demonstrates the use of CSS guards in less file.
HTML
<!DOCTYPE html> < head > < link rel = "stylesheet" href = "style.css" type = "text/css" /> </ head > < body class = "hello" > < h1 class = "button" >neveropen</ h1 > < h3 class = "button1" >< b >CSS Guards</ b ></ h3 > </ body > </ html > |
style.less:
CSS
@my-option: true; @ color : green ; @black: white ; @ background : black ; .my-optional-style() when (@my-option=true) { .button { color : @color; text-align : center ; } .button 1 { color : @ black ; text-align : center ; } .hello { background-color : @background; } } .my-optional-style(); |
Syntax: To compile the less file to a CSS file, write the following command.
less style.less style.css
Execute the above command, it will create the “style.css” file automatically with the following code.
style.css
CSS
.button { color : green ; text-align : center ; } .button 1 { color : white ; text-align : center ; } .hello { background-color : black ; } |
Output:
Example 2: This example, demonstrates the use of CSS guards in less file.
HTML
<!DOCTYPE html> < head > < link rel = "stylesheet" href = "New.css" type = "text/css" /> </ head > < body > < div > < h2 class = "cont" >Welcome to neveropen</ h2 > < h3 class = "style" >< b >CSS Guards</ b ></ h3 > </ div > </ body > </ html > |
New.less:
CSS
@primary: green ; @usedVariable: global; .mixin() { @usedVariable: mixin; .cont when (@usedVariable = mixin) { color : @primary; text-align : center ; } .style when (@usedVariable = mixin) { text-align : center ; } @usedVariable: mixin; } .mixin(); |
Syntax: To compile the less file to a CSS file, write the following command.
less New.less New.css
Execute the above command, it will create the “New.css” file automatically with the following code.
New.css
CSS
.cont { color : green ; text-align : center ; } .style { text-align : center ; } |
Output:
Reference: https://lesscss.org/features/#css-guards-feature