PHenderson
PHenderson

Reputation: 153

Twitter Bootstrap 3 - how can I switch from a horizontal button group to vertical button group based on screen size?

I have a horizontal button group that I would like to have it switch to a vertical button group with the screen size is extra small (-xs). Is there a way to do that with Bootstrap 3 classes?

Upvotes: 15

Views: 5535

Answers (2)

Marco
Marco

Reputation: 369

If you use the pure bootstrap approach suggested by Duvrai and are using Razor in ASP.NET, you could avoid the literal duplication of code by creating an @helper that can be reused. As such, the example provided would become

@helper ReusedBlock(string clazz){
<div class="@clazz">
  <button class="btn">Hello</button>
  <button class="btn">World</button>
</div>
}

and then it would be used simply like this

@ReusedBlock("btn-group hidden-xs")
@ReusedBlock("btn-group-vertical visible-xs")

This is particularly useful if the reused block is complex and makes the code cleaner and easier to understand and maintain.

Note: you can pass any number of arguments to the defined helper, you just need to include them in its definition.

Upvotes: 0

Duvrai
Duvrai

Reputation: 3456

Using jquery to detect the window size and adapt the class of the menu correspondingly:

<div class="btn-group" id="responsive">
  <button class="btn">Hello</button>
  <button class="btn">World</button>
</div>

<script>
$(window).resize(function() {
  if ($(window).width() < 408) {
    $('#responsive').removeClass('btn-group');
    $('#responsive').addClass('btn-group-vertical');
  } else {
    $('#responsive').addClass('btn-group');
    $('#responsive').removeClass('btn-group-vertical');
  }
});
</script>

With pure bootstrap you would make two menus: a horizontal and a vertical one:

<div class="btn-group hidden-xs">
  <button class="btn">Hello</button>
  <button class="btn">World</button>
</div>

<div class="btn-group-vertical visible-xs">
  <button class="btn">Hello</button>
  <button class="btn">World</button>
</div>

In an ideal world you would do this using only media queries in css, but adding custom media queries to bootstrap may be a bit more complex.

Upvotes: 17

Related Questions