How to centre align text or content vertically with CSS
The above has long been a slightly confusing point since the dawn of the semantic web, when designers and developers moved away from using table elements. If you Google the above, you'll get a mixture of answers, ranging from absolute positioning to negative margins and use of line height. Yet, the simplest answer lies in the past.
For a variable amount of text that you want to centre vertically and horizontally, you can use display: table-cell and vertical-align: middle.
Example 1: centred text in a div of a specific height and width:
.wrapper { display: table-cell; width: 200px; height: 150px; text-align: center; vertical-align: middle; border: 1px dotted #656565; }
If you want to get creative with your styling, an easy example would be to start with some padding by simply throwing in another div!
Example 2: centred text in a div of specific width and height, with some padding inside:
.wrapper { display: table-cell; width: 200px; height: 150px; text-align: center; vertical-align: middle; border: 1px dotted #656565; } .inner { padding: 10px; }
Example 3: centred text in a div of specific width and height, with some padding inside, floated left!:
.content { overflow: hidden; } .floatme { float: left; } .wrapper { display: table-cell; width: 200px; height: 150px; text-align: center; vertical-align: middle; border: 1px dotted #656565; } .inner { padding: 10px; }
Before jumping in, be aware of the following issues:
- Should you want to float the wrapper element or use any position but static, it won't work on the wrapper element – you will need a wrapper outside of it. This does lead to heavier mark-up, but, for the sake of vertically centred text, no matter how many lines of text are within the element, it's still a win. See example three.
- IE < 8 does not recognise display: table-cell – this is a fairly big one! Should IE be important to you, use conditional CSS to detect IE 6 and 7 and implement a polyfill .htc file as described here.
You can see this used to great effect on the recently updated Kent County Cricket Club website carousel; should you have any questions, you can post them in comments below.