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?
Instead of tying myself in a knot with hard-to-write and hard-to-maintain CSS (that also needs careful cross-browser validation!) I find it far better to give up on CSS and use instead wonderfully simple HTML 1.0:
This accomplishes everything the original poster wanted, and is robust and maintainable.
This will work way back to IE6!
<!DOCTYPE html>
is required on IE6 too! [ will force IE6 default strict mode as well ].( of course, the box coloring is for demo purposes only )
This works for me. Width and hight of the outer div can be defined.
Here the code:
enter image description here 100% it works
https://jsfiddle.net/Mangesh1556/btn1mozd/4/
text align-center on parent element, display inline-block on child element. This will center all most anything. I believe its call a "block float".
This is also a good alternative for float's, good luck!
To center align both vertically and horizontally: