Vertical Centering Absolutely Positioned Block

Ok, so I am trying to center a div with dynamic content ( and its width and height are unknown , because the text occupies an unknown space and wraps an unknown number of lines).

Per this post , I managed to center the div horizontally .

However, when I apply the same principle to vertical centering, the block moves only 50% down (and does not move at all).

JSFiddle of my problem here: http://jsfiddle.net/nMqJG/2/ ; as you can see, it is centered horizontally, but not vertically ...

Thanks, and any help is appreciated,

Edit: FYI, I am using FF10.0.2

+1
html css
source share
3 answers

If you don't need to support older browsers, use display: table-cell . Details here

HTML:

 <div class="wrapper"> <div class="in"> DYNAMIC CONTENT DYNAMIC CONTENT DYNAMIC CONTENT DYNAMIC CONTENT </div> </div> 

CSS

 .wrapper{ border:1px solid #F00; width:200px; height:200px; display: table-cell; vertical-align: middle } .in{ border:1px solid #00F; } 

Fiddle: http://jsfiddle.net/nMqJG/25/

+1
source share

You need to think in terms of% width and% height:

 .wrapper{ border:1px solid #F00; width:200px; height:200px; position:relative; } .in{ float:left; width:100px; height:100px; margin:25%; display:inline-block; border:1px solid #00F; } <div class="wrapper"> <div class="in"> DYNAMIC CONTENT </div> </div> 

If you use fixed pixel widths, you will need to think about how your% margin will affect internal divs based on space limitations.

For example, you have a container of size 200x200 with an internal DIV of size 100x100. Therefore, if you move the interior by 25% of the appearance, you move 200 * .25 = (50 pixels). 50 + 100 + 50 - 200, which centers your inner div from all sides.

0
source share

Will this work for you? (Borrowing code and tuning from another answer)

 .wrapper{ border:1px solid #F00; width:200px; height:200px; position:absolute; } .in{ left: 25%; right: 25%; top: 25%; bottom: 25%; position: absolute; display:inline-block; border:1px solid #00F; } <div class="wrapper"> <div class="in"> DYNAMIC CONTENT </div> </div> 

Using absolute positioning and 25% on all top / left / bottom / bottom sides, you should get your inner div in the middle regardless of the size or position of the wrapper on the page.

0
source share

All Articles