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.
+6
6 answers
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
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
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