Centering both horizontally and vertically
Actually, having the height and width in percents makes centering it even easier. You just offset the left and top by half of the area not occupied by the div.
So if you height is 40%, 100% - 40% = 60%. So you want 30% above and below. Then top: 30% does the trick.
See the example here: http://dabblet.com/gist/5957545
Centering only horizontally
Use inline-block. The other answer here will not work for IE 8 and below, however. You must use a CSS hack or conditional styles for that. Here is the hack version:
See the example here: http://dabblet.com/gist/5957591
.inlineblock {
display: inline-block;
zoom: 1;
display*: inline; /* ie hack */
}
EDIT
By using media queries you can combine two techniques to achive the effect you want. The only complication is height. You use a nested div to switch between % width and
http://dabblet.com/gist/5957676
@media (max-width: 1000px) {
.center{}
.center-inner{left:25%;top:25%;position:absolute;width:50%;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}
@media (min-width: 1000px) {
.center{left:50%;top:25%;position:absolute;}
.center-inner{width:500px;height:100%;margin-left:-250px;height:300px;background:#f0f;text-align:center;max-width:500px;max-height:500px;}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…