I have a div
element which contains text, and I want to align the contents of this div
vertically center.
Here is my div style:
#box {
height: 170px;
width: 270px;
background: #000;
font-size: 48px;
color: #FFF;
text-align: center;
}
<div id="box">
Lorem ipsum dolor sit
</div>
What is the best way to do this?
Wherever you want vertically center style means you can try
display:table-cell
andvertical-align:middle
.Example:
The simple and versatile way is (as michielvoo table approach):
Using this attribute (or a equivalent class) on a parent tag works even for many childs to align:
I saw the previous answers, and they will work only for that width of screen (not responsive). For the responsive you have to use flex.
Example:
Flexible approach
I needed a row of clickable elephants, vertically centered, but without using a table to get around some Internet Explorer 9 weirdness.
I eventually found the nicest CSS (for my needs) and it's great with Firefox, Chrome, and Internet Explorer 11. Sadly Internet Explorer 9 is still laughing at me...
Obviously you don't need the borders, but they can help you see how it works.
All credit goes to this link owner @Sebastian Ekström Link; please go through this. See it in action codepen. By reading the above article I also created a demo fiddle.
With just three lines of CSS (excluding vendor prefixes) we can do it with the help of a transform: translateY vertically centers whatever we want, even if we don’t know its height.
The CSS property transform is usually used for rotating and scaling elements, but with its translateY function we can now vertically align elements. Usually this must be done with absolute positioning or setting line-heights, but these require you to either know the height of the element or only works on single-line text, etc.
So, to do this we write:
That’s all you need. It is a similar technique to the absolute-position method, but with the upside that we don’t have to set any height on the element or position-property on the parent. It works straight out of the box, even in Internet Explorer 9!
To make it even more simple, we can write it as a mixin with its vendor prefixes.