Use CSS for class and media queries

I have a menu bar that opens and closes. Its closed state also looks like the screen is small enough. So I basically have the same styles two times: once in the class and once as a media query.

Is there a way to avoid this?

Edit ¹:

I want to avoid media queries and class style. It would be nice if there was some clever way of applying the same style using both a class and a media query.

Edit ²:

Sample code (for illustrative purposes):

menu {
    width: 100px;
}

menu.closed { /*triggered via class addition in javascript */
    width:10px;
}

@media (max-width:1000px) {
    menu { /*notice how this is the same as the closed class*/
        width:10px;
    }
}

      

+3


source to share


1 answer


You have achieved the most compact code using pure CSS.

To achieve even more dry CSS, you can use a CSS preprocessor.

They are marked as ... Some of them and ...


An example is smaller :



@small-menu: 10px;

menu {
    width: 100px;
}

menu.closed {
    width: @small-menu;
}

@media (max-width:1000px) {
    menu {
        width: @small-menu;
    }
}

      


Sass example :

$small-menu: 10px;

menu {
    width: 100px;
}

menu.closed {
    width: $small-menu;
}

@media (max-width:1000px) {
    menu {
        width: $small-menu;
    }
}

      

+4


source







All Articles