Search code examples
htmlcssflexboxvertical-alignment

Vertically align the content of a <div> contained within another <div>


I finally created boxes that will line up horizontally, take up equal space, and be of equal height if one box has more content than the others. Moreover, if the screen width shrinks below 600 pixels, the boxes line themselves up vertically. These are attributes which I don't want to lose.

However, I am having a hard time finding a way to vertically align the contents of the boxes/divs. I want the text "1" "3" "4" to be in the vertical center of the divs they are contained within. How can I go about doing that?

JFiddle Link

.fwrapper {
  display: flex;
  #justify-content: space-around;
  justify-content: flex-start;
  background: #eee;
}

.fbox {
  width: 100%;
  padding: 1%;
  margin: 1%;
}

@media only screen and (max-width: 600px) {
  .fwrapper {
    display: block;
  }
  .fbox {
    width: inherit;
    margin: .6em;
  }
}

.pnbox {
  background: #ccc;
  border: 1px solid black;
  box-shadow: 4px 4px 4px #999;
  border-radius: 5px;
}
<div class="fwrapper">
  <div class="fbox pnbox">1</div>
  <div class="fbox pnbox">2 this is a lot of text2 this is a lot of text 2 this is a lot of text 2 this is a lot of text 2 this is a lot of text 2 this is a lot of text 2 this is a lot of text 2 this is a lot of text t </div>
  <div class="fbox pnbox">3</div>
  <div class="fbox pnbox">4</div>
</div>


Solution

  • Just make the flex items into (nested) flex containers, and apply flex alignment properties.

    Add this to your code:

    .fbox {
      display: flex;
      align-items: center;     /* vertical alignment */
      justify-content: center; /* horizontal alignment */
    }
    

    revised demo

    More details: https://stackoverflow.com/a/33049198/3597276