DD
...">

Center of a small div in a large div vertically and horizontally

My code is as follows:

<div id="bigDiv"> <div id="smallDiv">DD</div> </div> 

My CSS is as follows:

 #bigDiv { border: 1px solid red; height: 300px; width: 300px; vertical-align: middle; } #smallDiv { border: 1px solid black; height: 100px; width: 100px; margin: 0 auto; } 

I want to center a small div vertically and horizontally inside a large div. Horizontal works, but the vertical does not work.

http://jsfiddle.net/4Gjxk/

+6
source share
6 answers

I believe this is the most straightforward solution with the least CSS. Since 100/300 = ~ .33, you can use a 33% margin as follows:

 #bigDiv { border: 1px solid red; height: 300px; width: 300px; } #smallDiv { border: 1px solid black; height: 100px; width: 100px; margin: 33%; } 

Updated jsFiddle here .

+3
source

Read the following: http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

If you can’t worry, do the following:

  #bigDiv { position: relative; /* Needed for position: absolute to be related to this element and not body */ border: 1px solid red; height: 300px; width: 300px; vertical-align: middle; } 

And change another to:

 #smallDiv { position: absolute; margin: auto; top: 0; bottom: 0; left: 0; right: 0; border: 1px solid black; height: 100px; width: 100px; } 

Here is the updated jsfiddle: http://jsfiddle.net/4Gjxk/1/

+8
source

Must be:

 #smallDiv{ position:absolute;//? relative? top:45%; left:45%; } 

This should be fair, but I'm sure someone will come up with a better method. Obviously, you could also make pixels, so top:100px;left:100px; will work and maybe better in your case :).

0
source

Try with absolute positioning. You just need to know the width of the element to place it right in the center.

  #bigDiv { border: 1px solid red; height: 300px; position: relative; vertical-align: middle; width: 300px; } #smallDiv { border: 1px solid black; height: 100px; left: 50%; margin: -50px auto 0 -50px; position: absolute; top: 50%; width: 100px; } 
0
source

add this to #smallDiv:

 margin-top: 100px; 
0
source

If you need to do this without knowing the exact size of the boxes (if they can change), this is a slightly hacky way to do this: http://jsfiddle.net/gXbqm/

 #bigDiv { border: 1px solid red; height: 300px; width: 300px; vertical-align: middle; display:table-cell } #smallDiv { border: 1px solid black; height: 100px; width: 100px; margin: 0 auto; vertical-align:center; } 

If you know that these divs will always be 100x100 and 300x300, although the Jonathan.cone solution is cleaner

0
source

All Articles