user254197 user254197 - 2 months ago 10
CSS Question

Media queries in less with variables-need global variables

I am looking for a solution where I define 1 variable globally and than overwrite it inside a media query - without putting the entire code in it (like LESS CSS set variables in media query?).

I thought something like that(defining):

@media (min-width: 768px) {
@BWInputHeight: 40px;
}

@media (max-width: 768px) {
//responsive screens
@BWInputHeight: 20px;
}


And using it like that:

.dataTables_filter input {
.form-control;
max-width: 135px;
display: inline-block;
height: @BWInputHeight;
padding: 1px 6px;
margin-right: 15px;
}


The problem here, "@BWInputHeight" is a undeclared variable. How can I solve this with LESS ?

Answer

You can sort of achieve this by using list arrays for each property and screen-width (like the below sample):

@BWInputHeight: '20px','40px','60px'; // Height of the button for min-width=320 and min-width=768 respectively
@minwidths: '320px','768px','1024px'; // The widths for which you need the media queries to be created

.loop-column(@index) when (@index > 0) { // Loop to iterate through each value in @minwidths and form the corresponding output
    .loop-column(@index - 1);
    @width:  extract(@minwidths, @index); // extracts width based on array index
    @media (min-width: e(@width)){
          .dataTables_filter input{
            height: e(extract(@BWInputHeight,@index)); // extracts button height for the corresponding screen width
            max-width: 135px;
            display: inline-block;
            padding: 1px 6px;
            margin-right: 15px;          
          }
    }
}

.loop-column(length(@minwidths)); // calling the function

Demo in Code-pen - Modify output area width to see difference and click the eye icon in CSS tab to see compiled CSS.

Note: As per this Stack Overflow thread, both dotless and less.js should be 99% compatible and hence I have given this answer. In case this doesn't work for you, I will happily have this answer removed.