June 27, 201412 yr I've been looking through pages of websites from Google about how to vertically align some text within a DIV and I can't get any to work. Surely there is a simple way of doing this like: vertical-align: middle; Can anyone advise?
June 27, 201412 yr You have a few options here. To use vertical-align: middle, you need an inline element, such as an image, or a table cell. One option is to create a div and give it a property display:table-cell along with vertical-align:middle. Another option, however, is to create a div wrapper with a child element positioned absolutely to the middle of the parent. Here is a JsFiddle with examples of both: http://jsfiddle.net/aMvaV/ The first div (div.one) is displayed as a table-cell. The second div (div.two) is positioned relatively and has an absolutely positioned child element that is positioned 50% top. Using this approach, you'd typically want the top value to be 50% minus half of the height of the content div (for when the content spans multiple lines). Hope this helps. Edited June 27, 201412 yr by Lyndsey
June 27, 201412 yr The table option being the most flexible of those that Lyndsey mentioned. You can use line-height also, just match it to the height of the continer, hover this only works on a single line of text. For that reason go with css tables. <div class="container"> <div class="table"> <div class="table-cell"> <p>Lorem ipsum.......</p> </div> </div> </div> .content { height: 200px; } .table { display: table; } .table-cell { display: table-cell; vertical-align: middle; } .table, .table-cell { width: 100%; height: 100%; } It's a good idea to abstract the table class into it's own class then use a container around any 'table' to set it's dimensions, then you can use this centering technique throughout your site as a component. One thing to note -- anything that is a block, or inline block element like an image that gets put inside the table cell may break outside of the container as the width: 100% only works for inline content. To fix this add the following to your table class: .table { display: table; table-layout: fixed; }
Create an account or sign in to comment