Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/Remove classes using media queries

My general question is how can one conditionally add or remove classes or ids to a particular class using css media queries alone? In the sample code below, for example, how could I add "Class_B" to all of the div's with "Class_A" when @media all and (max-width: 1000px) and (min-width: 700px)?

<div class="Class_A"><div>

My specific case: I'm using Twitter Bootstrap v3.2.0. I have a header with a series of buttons in it like so:

<button class="btn navbar-btn">FooA</button>
<button class="btn navbar-btn">FooB</button>
<button class="btn navbar-btn">FooC</button>

When the screen jumps from medium (md) to small(sm), I would like to add the class "btn-sm" to all of those elements. How can I do that most efficiently/elegantly? (I would prefer not to use JS or add any additional libraries if that's possible)

I realize I could add an arbitrary class to all those buttons like "btn-sm-duplicate" and only define it when the browser reaches a certain specification like the code below. However, it seems ugly to create a duplicate class when it's really not nec... Can you suggest something?

@media all and (max-width: 1000px) and (min-width: 700px) {
       btn-sm-duplicate{

::Copy/Paste all the attributes of btn-sm from bootstrap::

       }
}  
like image 520
Afflatus Avatar asked Jul 16 '14 16:07

Afflatus


1 Answers

You cannot do this with CSS alone. One approach would be to take advantage of extend in a CSS pre-processor like LESS.

LESS example:

@media (max-width: 991px) {
    btn-sm-duplicate{
        &:extend(.btn-sm);
    }
}

Another approach would be to use Javascript to add the class based on screen size. A library like Modernizr.mq makes this pretty easy.

like image 147
Steve Sanders Avatar answered Oct 24 '22 14:10

Steve Sanders