Ivan Ivan - 1 month ago 9
CSS Question

Can't align vertically text inside a div wich is aligned horizontally with others

I have 4 divs aligned horizontally in the same line. I'm trying to center vertically the second and third through 'vertical-align' attribute with no success.



#container {
width:100%;
height:45px;
background-color:yellow;
}

#left {
width:100px;
height:45px;
float:left;
background-color:red;
}

#center1 {
width:100px;
height:45px;
display:inline-block;
background-color:green;
vertical-align: center;
word-break: break-word;
}

#center2 {
width:100px;
height:45px;
display:inline-block;
background-color:orange;
word-break: break-word;
}

#right {
width:100px;
height:45px;
float:right;
background-color:blue;
}

<div id="container">
<div id="left">&nbsp;</div>
<div id="center1">Center 1</div><div id="center2">Center 2 Center 3</div>
<div id="right">&nbsp;</div>
</div>





View in Fiddle

I don't want to align second and third content with 'position: relative; top: Xpx' or 'line-height: 45px;' due to second and third can have until two lines so I need to stay correctly aligned with one line and two lines.

Any idea?

Thank so much!

Answer

Just add display: inline-flex; and align-items: center; to #center1 and #center2.

Edit: Dont forget to float them left.


Example:

#container {
  width:100%;
  height:45px;
  background-color:yellow;
}

#left {
  width: 100px;
  height:45px; 
  float:left;
  background-color:red;
}

#center1 {
  width: 100px;
  height:45px;
  background-color:green;
  float: left;
  display: inline-flex;
  align-items: center;
}

#center2 {
  width: 100px;
  height:45px;
  background-color:orange;
  float: left;
  display: inline-flex;
  align-items: center;
}

#right {
  width: 100px;
  height:45px; 
  float:right;
  background-color:blue;
}
<div id="container">
  <div id="left">&nbsp;</div>
  <div id="center1">Center 1</div><div id="center2">a long line of text!</div>
  <div id="right">&nbsp;</div>
</div>