I was trying to apply the CSS property vertical-align: middle on an element but no luck, it was not working as expected.
Here is an example of non-functioning code :
.container {
background-color: red;
height: 50px;
width: 100px;
}
.text {
vertical-align: middle;
}
The first option would be to set a line-height on the element you want to center vertically :
.container {
background-color: red;
height: 50px;
width: 100px;
}
.text {
vertical-align: middle;
line-height: 50px;
}
The second option would be to use display table on the parent .container, and display table-cell on the element you want to center vertically :
.container {
background-color: pink;
height: 50px;
width: 100px;
display: table;
}
.text {
vertical-align: middle;
display: table-cell;
}
Latest comments (7)
This is 2021, not 2005. Use display:flex; align-items:center; justify-content:center;
I use flex most of the time, it's so easy and simple. However, I was in a situation where we were recommended not to use it because we were injecting code on exciting websites.
"Injecting code on exciting websites"?!? What in the blazes does that even mean?
I don't know if I'm using to correct words, I'm not a native English speaker.
We had a special format of ads to display on our publishers sites. So we needed do add some basic CSS and JavaScript to avoid any conflict between the ad and the shape of the website.
You can't tell if it works or not only with css...
If you look at the documentation, you'll find there's an html context to use vertical-align
Vertical-align applies to all inline-level elements, not just inline and inline-block. So it also applies to elements that are inline-table, inline-flex, and inline-grid. (Plus inline list-item in Firefox)
Thanks a lot for the precision, I didn't know about that.