1

In a responsive layout, I have two columns. The left column is the sidebar and the right column is the content.

Using a media query, when the screen width is tiny, the columns turn to 100% width and stack on top of each other.

In this case, I want the sidebar (the first div) to appear beneath the content (the second div).

I tried using float: right on a small screen once it's at 100%, but at 100% width, the float apparently doesn't matter.

.left, .right {
  width: 100%;
  float: left;
  background: green;
}
.left {
  float: right;
  background: red;
}
.half {
  width: 50%;
}
.space {
  width: 100%;
  display: block;
  height: 40px;
}

And on the page:

<div class="left half"> <!-- To mimic full screen size -->
Left
</div>
<div class="right half">
Right
</div>

<div class="space"></div>

<div class="left"> <!-- To mimic small screen size -->
Left
</div>
<div class="right"><!-- This should appear first -->
Right
</div>

Here is the fiddle: https://jsfiddle.net/ph09frvw/

I'm sure this is not the first time someone wanted to wrap the sidebar under the content, I just haven't been able to find a solution.

MultiDev
  • 10,389
  • 24
  • 81
  • 148
  • samething done in Bootstrap http://stackoverflow.com/questions/20979062/bootstrap-right-column-on-top-on-mobile-view – kakurala Apr 11 '16 at 14:06

3 Answers3

2

You can use display: flex and use the order property to change the order of the <div> elements. While floating can be helpful for horizontal alignment, it will be of little help for vertical alignment, Here is an example:

.flex {
  display: flex;
  flex-flow: row wrap;
}
.left {
  order: 2;
  flex: 1 0 50%;
  background: red;
}
.right {
  order: 1;
  flex: 1 0 50%;
  background: green;
}
.full {
  margin-top: 20px;
}
.full > .left,
.full > .right {
  flex: 1 0 100%;
}
<div class="flex">
  <div class="left">
    Left
  </div>
  <div class="right">
    Right
  </div>
</div>

<div class="flex full">
  <div class="left">
    Left
  </div>
  <div class="right">
    Right
  </div>
</div>
Nico O
  • 13,762
  • 9
  • 54
  • 69
0

You could use the display:flex; property combined with flex-direction to reorder your divs. Ref: https://css-tricks.com/almanac/properties/f/flex-direction/

BasySilver
  • 420
  • 2
  • 8
0

Remember to reference your related class-names in your HTML elements' class attribute.

Your CSS display:block should do the trick, else try something like: float: left

When you use: display:block on a div element, you do not need to specify width:100% as it should automatically span across the width if it is not hindered by anything else.

Make sure the position of these elements are "relative", else it may not work as expected; it may be stated globally that some specific tags should be displayed "absolute" and that may break what you're trying to achieve.