Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch height with flexbox align-items center

Tags:

html

css

flexbox

I have a div with display: flex; flex-direction: row;. The children of this div take the full height unless I specify align-items: center. Code below -

.row {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100px;
  background: beige;
  border: 1px solid red;
  margin: 10px 0;
}

.row2 {
  align-items: center;
}

.row-item {
  border: 1px solid green;
}

.item1,
.item3 {
  width: 100px;
}

.item2 {
  flex: 1;
}
<div class="row row1">
  <div class="row-item item1">1</div>
  <div class="row-item item2">
    <div> 2.1 </div>
    <div> 2.2 </div>
  </div>
  <div class="row-item item3">3</div>
</div>

<div class="row row2">
  <div class="row-item item1">1</div>
  <div class="row-item item2">
    <div> 2.1 </div>
    <div> 2.2 </div>
  </div>
  <div class="row-item item3">3</div>
</div>

JSFiddle

What I want to achieve is that 2.1 and 2.2 should take 50px (50%) height and should have its content middle aligned vertically. They should also stretch the full available space horizontally (like width: auto or 100%). Then if 2.1 is not present, 2.2 should take 100px height and should be vertically aligned to middle.

like image 825
jaibatrik Avatar asked Nov 08 '22 22:11

jaibatrik


1 Answers

You need to make row-items a flex box and apply align-items: center; to them

This is the code that you should add

.row1 .row-item {
  display: flex;
  align-items: center;
}

See result below :

.row {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 100px;
  background: beige;
  border: 1px solid red;
  margin: 10px 0;
}

.row2 {
  align-items: center;
}

.row-item {
  border: 1px solid green;
}

.row1 .row-item {
  display: flex;
  flex-wrap: wrap;
}

.row1 .row-item div {
  width: 100%;
  border: 1px solid blue;
  display: flex;
  align-items: center;
}

.item1,
.item3 {
  width: 100px;
}

.item2 {
  flex: 1;
}
<div class="row row1">
  <div class="row-item item1">1</div>
  <div class="row-item item2">
    <div> 2.1 </div>
    <div> 2.2 </div>
  </div>
  <div class="row-item item3">3</div>
</div>

<div class="row row2">
  <div class="row-item item1">1</div>
  <div class="row-item item2">
    <div> 2.1 </div>
    <div> 2.2 </div>
  </div>
  <div class="row-item item3">3</div>
</div>
like image 195
Chiller Avatar answered Nov 15 '22 06:11

Chiller