Search code examples
cssresponsive-designmedia-queriesdrydynamic-css

Use CSS for class and media query


I have a menu bar that slides opened and closed. Its closed state is also what it looks like when the screen is sufficiently small. So, I basically have the same styles twice: once as a class and once as a media query.

Is there any way to avoid this?

Edit ¹:

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

Edit ²:

Code example (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;
    }
}

Solution

  • You have achieved the most compact code using pure CSS.

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

    They are tagged as . Some of them are , and .


    Less example:

    @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;
        }
    }