Michael
Michael

Reputation: 16142

Align divs vertically using flexbox

I'm trying to align three div blocks vertically using flexbox.

I can get them horizontally aligned correctly, however not vertically.

What am I doing wrong?

.banner {
  padding-top: 10px;
  padding-bottom: 10px;
  background-color: #01b9d5;
  color: white;
  height: 55px;
}
.banner-align {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid green;
}
.banner-hero {
  flex: 1;
  align-self: center;
  max-width: 50%;
  border: 1px solid red;
  text-align: center;
  display: inline-block;
}
.banner-left {
  align-self: flex-start;
  flex: 1;
  border: 1px solid green;
  display: inline-block;
}
.banner-right {
  align-self: flex-end;
  flex: 1;
  text-align: right;
  border: 1px solid yellow;
  display: inline-block;
}
<div class="banner">
  <div class="container banner-align">
    <div class="banner-left">
      Left Block
    </div>
    <div class="banner-hero">
      <b>Title</b>
    </div>
    <div class="banner-right">
      Right block
    </div>
  </div>
</div>

Here is a fiddle: https://jsfiddle.net/zqc1qfk1/1/

Upvotes: 10

Views: 12257

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 372149

Simply enable wrap on the container and give each flex item a width: 100%:

.banner-align {
  display: flex;
  flex-wrap: wrap;
}

.banner-align > * {
   flex: 0 0 100%;
 }

Now each flex item consumes all the space in the row, forcing other elements to create new rows.

revised fiddle

Upvotes: 6

Lee Saxon
Lee Saxon

Reputation: 457

align-items: center on your flex parent centers everything vertically. However, using align-self: [anything but center] on the children overrides this.

Edit:

oops, as someone else pointed out, you're not getting the align-self effect in the original fiddle because the parent's height wasn't set and so it was only as tall as it needed to be to contain the children. If the children hadn't all been the same height, you would've seen them staggered.

If you're trying to have them all centered, you can get rid of the align-self properties and let the one align-items: center on the parent do that work. If you wanted them staggered, you don't need the one align-items: center on the parent.

Upvotes: 1

Nikhil Nanjappa
Nikhil Nanjappa

Reputation: 6652

You are missing the flex-direction:column attribute of flex.

By default any flex container has a flex-direction: row & that is the reason its moving horizontally & not vertically. You need to specify this explicitly.

Here is more about it

.banner-align {
  display: flex;
  align-items: center;
  justify-content: center;
  border:1px solid green;
  flex-direction: column;
}

Updated the Fiddle.

Upvotes: 12

Related Questions