I want to center a div which is added inside another div.
<div id="outerDiv">
<div id="innerDiv">
</div>
</div>
This is the CSS I am currently using.
#outerDiv{
width: 500px;
height: 500px;
position:relative;
}
#innerDiv{
width: 284px;
height: 290px;
position:absolute;
top: 50%;
left:50%;
margin-top: -147px;
margin-left: -144px;
}
As you can see,the approach I use now depends on values for width and height of innerDiv
.If the width/height changes, I will have to modify the margin-top
and margin-left
values.Is there any generic solution that I can use to center the innerDiv
always irrespective of its size?
I figured out that using margin:auto
can horizontally allign the innerDiv to the middle.But what about vertical allign middle?
Fiddle Link < http://jsfiddle.net/dGHFV/2515/>
Try this
You can do this with a simple javascript (jQuery) block.
CSS:
Javascript:
Another way is using Transform Translate
Outer Div must set its
position
torelative
orfixed
, and the Inner Div must set itsposition
toabsolute
,top
andleft
to50%
and apply atransform: translate(-50%, -50%)
.Tested in:
Vertically centering div items inside another div
Just set the container to
display:table
and then the inner items todisplay:table-cell
. Set aheight
on the container, and then setvertical-align:middle
on the inner items. This has broad compatibility back as far as the days of IE9.Just note that the vertical alignment will depend on the height of the parent container.
for innerdiv which do not specify it's height value,there is no pure css solution to make it vertically centered.a javascript solution could be get the innerdiv's offsetHeight,then calculate the style.marginTop.
I have been using the following solution since over a year, it works with IE 7 and 8 as well.