How can I move a div from top to bottom on mobile layouts? [duplicate]

牧云@^-^@ 提交于 2020-05-10 04:46:01

问题


I am using Bootstrap 4, but if it works on version 3, it should work on v4.

I have 2 divs within a column like so:

<div class="row">
    <div class="col-xs-12">
        <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
        <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
    </div>
</div>

Is there a way I can get the divs to swap around on a mobile device? I do not want to use any JavaScript here; I would like to use Bootstrap classes only, if possible.

If it is not possible with Bootstrap, then CSS-only please.


回答1:


This can be achieved using CSS' flexbox.

  • Add a new selector .col-xs-12 with the following properties:
    • display: flex; tells the children to use the flexbox model
    • flex-direction: column-reverse; will ensure that the children flow from bottom to top (instead of the default left to right)

Run the below Snippet in full screen and resize the window to see the order of the elements change.

@media only screen and (max-width: 960px) {
  .col-xs-12 {
    display: flex;
    flex-direction: column-reverse;
  }
}
<div class="row">
  <div class="col-xs-12">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>

A Bootstrap method

This can also be achieved using Bootstrap:

  • Add the following classes to the container:
    • d-flex to make the container use flexbox
    • flex-column-reverse to order the children in reverse order on small screens
    • flex-sm-column to order the children in normal order on larger screens

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<div class="row">
  <div class="col-xs-12 d-flex flex-column-reverse flex-sm-column">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>



回答2:


The following code works for me:

@media only screen and (max-width: 768px) {
  .xs-column-reverse {
    display: flex;
    flex-direction: column-reverse;
  }
}
<div class="row">
  <div class="col-xs-12 xs-column-reverse">
    <div>TOP ON DESKTOP, BOTTOM ON MOBILE</div>
    <div>BOTTOM ON DESKTOP, TOP ON MOBILE</div>
  </div>
</div>



回答3:


.col-xs-12 { height: 200px; position:relative; }
.col-xs-12 div { position:absolute; top:0; left: 0; width:100%; }
.col-xs-12 div:last-child { top: auto; bottom: 0; }

@media (max-width: 480px) {
    .col-xs-12 div { top:auto; bottom:0; }
    .col-xs-12 div:last-child { top: 0; bottom: auto; }
}


来源:https://stackoverflow.com/questions/33260188/how-can-i-move-a-div-from-top-to-bottom-on-mobile-layouts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!