Erik Hofer
Erik Hofer

Reputation: 2656

Bootstrap 4: switch between cols on mobile

I've built a standard layout with a sidebar using Bootstrap's grid system (EDIT: I'm using Bootstrap 4 but could still switch). It looks like this:

<div class="row">
  <div class="col-md-3">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>

enter image description here

On mobile, the red area would be above the green one. I need to be able to switch between them in a way that is more convenient than scrolling, for example a switch button:

enter image description here

Also note the different oder of elements in the green area.

Is there a smart way to do this? Or do I have to alter the dom with JavaScript? Thanks in advance :)

Upvotes: 4

Views: 1827

Answers (2)

Carol Skelly
Carol Skelly

Reputation: 362840

You can use jQuery to toggle one of the BS4 flexbox utility classes. For example, apply the flex-last on the first (col-md-3) column.

To switch the order on mobile using a button, toggle the flex-last class...

$('#btnToggle').click(function(){
    $('.col-md-3').toggleClass('flex-last');
})

EDIT: To show only one at a time (switch the visibility of the 2 divs using a button) toggle the hidden-sm-down class instead...

$('#btnToggle').click(function(){
    $('.col-md-3, .col-md-9').toggleClass('hidden-sm-down');
})

Demo


In Bootstrap 4, column order can be toggled using CSS only, but this switches the cols based on screen width, and therefore is not triggered by the button.

<div class="row">
  <div class="col-md-3 flex-last flex-md-unordered">
    ...
  </div>
  <div class="col-md-9">
    <div class="row">
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
      <div class="col-md-4">...</div>
    </div>
  </div>
</div>

Update

As of Bootstrap 4 Beta 3, the ordering classes are named order-*, such as order-1, order-md-2, etc..

Upvotes: 2

Matej
Matej

Reputation: 9835

Bootstrap 4 uses Flexbox, which means you could utilise the order in which things are displayed.

As usual, you can specify how it's displayed on different viewports using classes like order-last and order-sm-unordered.

flexbox/order documentation

Upvotes: 0

Related Questions