0

The goal is to vertically center text in a div. This answer suggested using display: flex and align-items: center, but it's not working.

Codepen: https://codepen.io/anon/pen/qgOJZg

<div id="messageBox" style="">
   <div class="message">YO THERE THIS ROCKS!</div>
</div>


#messageBox {
    min-width: 150px;
    padding: 15px 35px;
    position: absolute;
    margin-left: 50%;
    bottom: 0;
    background: #424242;
    color: #FFF;
    cursor: pointer;
    text-align: center;
    border-radius: 5px 5px 0 0;
    font-family: "Lato";
    font-size: 17px;
    display: flex;
    align-items: center;
    justify-content: center;
}
Asiya Fatima
  • 1,388
  • 1
  • 10
  • 20
Crashalot
  • 33,605
  • 61
  • 269
  • 439

3 Answers3

2

There is so much to explain. But for now, just take a look at updated fiddle.

First of all, your container has a height of its content which is your textbox and nothing more than that, so textbox is basically in the center of its container. But when you give it a height, you would see it's not center. Due to the nature of flex-box, it has a flex-direction: row by default. So you're going to change that to column ( which is what I had done in provided jsFiddle ), and that's pretty much it.

There were some modest changes in the structure of CSS as well, but you'll find 'em out yourself; no need to explain.

As a further investigation, position: absolute will make a child out of flex-flow like it's not a descendant at all. When you're working with flex-box, you don't need absolute-positioned elements most of the time.

Again, as another further read, please check this great article about flex-box at css-tricks.com; covered everything and super simple to learn stuff.

mrReiha
  • 908
  • 6
  • 24
1

Just add set your #messageBox to this

#messageBox {
  display: flex;
  justify-content: center;
  flex-direction: column;
  text-align: center;
}

Live example: https://codepen.io/anon/pen/VgvEyY

TesoMayn
  • 69
  • 1
  • 6
1

@Crashalot: by using height we can achieve but you also vertically center by using this code also.

#messageBox { 
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.message {
  position: relative;
  min-width: 150px;
  padding: 15px 35px;
  background: #424242;
  color: #FFF;
  cursor: pointer;
  cursor: pointer;
  text-align: center;
  border-radius: 5px 5px 0 0;
  font-family: "Lato";
  font-size: 17px;
}
<div id="messageBox" style="">
   <div class="message">YO THERE THIS ROCKS!</div>
</div>
Asiya Fatima
  • 1,388
  • 1
  • 10
  • 20