Get screen width and calculate max value
css, less
Solution
Multiple questions there, so will answer them one by one.
- Yes, you can get the available screen height just like you would do in plain JavaScript using `window.screen.availWidth`. LESS supports Javascript statements when provided within backticks.
- For getting the maximum among two values you can use the built-in `max()` function in Less like `max(@var1, @var2)`. In this `@var1` and `@var2` are the two values for comparison. Note that both of them should be in the same unit for comparison. If not it will just output `max(val1, val2)` as output (which is what is happening in your case).
- For assigning the unit, that was one of the ways for earlier versions of LESS. Now it has a built in function called `unit()` which can be used like `unit(@var,px)`. This function actually works pretty much the same way like `~"`15*@{fSize}`px"` (Note the backticks within the quotes, this is why your second height property didn't work).
Overall, your code can be done as follows:
.def(@fSize){
@defHeight: `window.screen.availHeight`; //This is for getting screen width
font-size: unit(@fSize, em); // The following are for assigning the units
line-height: unit(1.5*@fSize,px);
height: unit(15*@fSize,px);
max-height: max(unit(@defHeight,px),unit(15*@fSize,px)) // This is for comparison
}
div#demo{
.def(1);
}
Compiled Output:
div#demo {
font-size: 1em;
line-height: 1.5px;
height: 15px;
max-height: 900px;
}
Problem
I have code like the below where I want to calculate and assign values for the `font-size`/`height` properties. In this I want to set the value of a property (say `max-height`) based on the maximum of available screen `height` and a calculated value (lets assume like the calculation done for the `height` property). Is there any way to do this in LESS? I tried with the `max` function but it doesn't seem to work. Also, for assigning px/em etc to the value, in one of the threads it is mentioned that it can be done using 0em + variable value. But is there a better looking way to do this? I tried like the second way shown in the below code but it is not working. The usecase mentioned here might sound silly but the actual cases are different and I have mentioned it this way only for simplicity. ``` .def(@fSize){ @defHeight: 100px; // Need this to be screen width font-size: 0em + @fSize; line-height: 0px + (1.5*@fSize); height: 0px + (15*@fSize); // Works fine //height: ~"15*@{fSize}px"; // Just prints 15*1px max-height: max(@defHeight, @fSize) // doesn't work } div#demo{ .def(1); } ```