Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically center multiple lines of flex items

Tags:

html

css

flexbox

I am trying to vertically align the child DIV of a wrapper but unfortunately not. Requirement is full-width and height of the screen wrapper with two child DIV vertically and horizontally centered. (height of the div is being handled by jQuery to make window height)

Note: I don't want to make child DIV width:100%

This is what I have tried:

.wrapper {
  width: 100%;
  height:100%;
  min-height:600px; /*just for example*/
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  background:#e1e1e1;
}
.row1 {
  background: #cdcdcd;
}
.row2 {
  background: #404040; color:#fff;
}
<div class="wrapper">
  <div class="row1">This is row one</div>
  <div class="row2">This is row two</div>
</div>
like image 718
Sanjeev Kumar Avatar asked Mar 12 '17 21:03

Sanjeev Kumar


1 Answers

An initial setting of a flex container is flex-direction: row. This means that the children of the container ("flex items") will line up in a row.

To override this default you can add flex-wrap: wrap to the container and give the items width: 100%, which forces one item per row. But you're saying this method isn't an option in this case.

So another option is to switch the container to flex-direction: column.

.wrapper {
  width: 100%;
  height:100%;
  min-height:600px; /*just for example*/
  display: flex;
  flex-direction: column; /* NEW */
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  background:#e1e1e1;
}
.row1 {
  background: #cdcdcd;
}
.row2 {
  background: #404040; color:#fff;
}
<div class="wrapper">
  <div class="row1">This is row one</div>
  <div class="row2">This is row two</div>
</div>
like image 101
Michael Benjamin Avatar answered Oct 22 '22 00:10

Michael Benjamin