简体   繁体   中英

How to display divs in a different order depending on screen size in Bootstrap 3?

I have a Bootstrap two column layout which collapses to one on narrow screens.

Bad ASCII art:

+-------------------+-------------------+
|  Div A            |  Div B1           |
|                   +-------------------+
|                   |  Div B2           |
|                   +-------------------+
|                   |  Div B3           |
+-------------------+-------------------+

collapsing to

+-------------------|
|  Div B1           |
+-------------------+
|  Div B2           |
+-------------------+
|  Div B3           |
+-------------------+
|  Div A            |
|                   |
|                   |
|                   |
|                   |
+-------------------+

A has class col-md-6 , B1-B3 are contained in a div B with class col-md-6 col-md-push-6 . This works just fine, but the layout would be even nicer as

+-------------------|
|  Div B1           |
+-------------------+
|  Div A            |
|                   |
|                   |
|                   |
|                   |
+-------------------+
|  Div B2           |
+-------------------+
|  Div B3           |
+-------------------+

Is that achievable with reasonable amounts of code?

It makes more sense when you design it thinking about what is going to look like on mobile first. A simple pull-right and pull-left and the right classes and architecture and you have no media hacks to use at all.

Disclaimer: Be careful, as the only downside to this is losing the tab sequence A1- B1- B2- B3 ;)

See the code

<div class="container">
    <div class="col-xs-12 col-md-6 pull-right">
         <div class="box">B1</div>
    </div>
    <div class="col-xs-12 col-md-6 pull-left">
         <div class="box a1">A1</div>
    </div>
    <div class="col-xs-12 col-md-6">
         <div class="box">B2</div>
    </div>
    <div class="col-xs-12 col-md-6">
         <div class="box">B3</div>
    </div>
</div>

CSS (this is only for demo beautification and distinction of boxes. You wont need this except the no-padding reset)

.container div{
    padding:0;
}
.box{
    background:red;
    height:40px;
    color:#fff;
    padding:10px;
    text-align:center;
    border:1px solid #111;
}
.box.a1{
    background:blue;
    height:120px;
}

See the demo

Use a media query to specify the new layout when it collapses. You can find all the information you need on media queries here: https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries

Barebones example:

@media (max-width: 700px) { 
    collapsed layout here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM