I love jumping on old bandwagons!
Here's a 2015 update to this answer. I started using CSS3 transform
to do my dirty work for positioning. This allows you to not have to make any extra HTML, you don't have to do math (finding half-widths of things) you can use it on any element!
Here's an example (with fiddle at the end). Your HTML:
With accompanying CSS:
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
What I do a lot these days is I will give a class to things I want centered and just re-use that class every time. For example:
css
.bigDiv {
width:200px;
height:200px;
background-color:#efefef;
position:relative;
}
.smallDiv {
width:50px;
height:50px;
background-color:#cc0000;
}
.centerThis {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
}
This way, I will always be able to center something in it's container. You just have to make sure that the thing you want centered is in a container that has a position
defined.
Here's a fiddle
BTW: This works for centering BIGGER divs inside SMALLER divs as well.