2

I am trying to vertically align two divs in a parent div.

The vertical align is straightforward, but I am also trying float the divs, one left and one right.

Is this possible to do?

.outer {
  background: red;
  height: 300px;
  display: flex;
  align-items: center;
}
.inner_right {
  background: blue;
  float: right;
}
.inner_left {
  background: yellow;
  float: left;
}
<div class="outer">
  <div class="inner_right">
    RIGHT MIDDLE
  </div>
  <div class="inner_left">
    LEFT MIDDLE
  </div>
</div>

https://jsfiddle.net/xh8rbnmh/

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
sci-guy
  • 2,394
  • 4
  • 25
  • 46

4 Answers4

2

body { margin: 0; }

.outer {
    display: flex;
    align-items: center;
    justify-content: space-between; /* 1 */
    background: red;
    height: 300px;
}

.inner_right {
    order: 1;                       /* 2 */
    /* float: right; */             /* 3 */
    background: aqua;
}

.inner_left {
    /* float: left; */              /* 3 */
    background: yellow;
}
<div class="outer">
  <div class="inner_right">RIGHT MIDDLE</div>
  <div class="inner_left">LEFT MIDDLE</div>
</div>
  1. methods for aligning flex items on main axis
  2. the flex order property can move elements around the screen
  3. floats are ignored in a flex formatting context
Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
1

Simple. You need to put your left div first in the markup. Then simply add margin: auto to the right div.

Note that if you need to retain the original markup (with the right div first, then the left div), flexbox allows you to order the divs using the intuitive order: property on each div.

I've updated the fiddle here: https://jsfiddle.net/v6facjnp/4/

jbyrd
  • 5,287
  • 7
  • 52
  • 86
0

This is alternative solution not using flexbox - noticed that margin has to be height of element.

  .outer {
  background: red;
  height: 300px;
  position:relative;
 }
.inner_right {
 background: blue;
 position:absolute;
 right:0px;
 top:50%;
 margin-top: -18px;
 }

.inner_left {
 background: yellow;
 position:absolute;
 top:50%;
 left:0px;
 margin-top: -18px;
}
panatoni
  • 735
  • 6
  • 13
0

First lets fix, some: left at the left, right at the right

<div class="outer">
  <div class="inner_left">
   LEFT MIDDLE
  </div>
  <div class="inner_right">
    RIGHT MIDDLE
  </div>
</div>

Second: Flex makes the elements to behave like blocks, discarding the float property. So we use margins and justify

.outer {
  background: red;
  height: 300px;
  display: flex;
  align-items: center;
  justify-content:flex-end; //Move all items to the right
}
.inner_right {
  background: blue;
}

.inner_left {
  background: yellow;
  margin-right:auto;//Move this to the left
}
LordNeo
  • 1,195
  • 1
  • 8
  • 21