开发者

Centering a percent-based div

Recently, a client asked that his site be percent-based rather than p开发者_如何学运维ixel-based. The percent was to be set to 80%. As you guys know, it is very easy to center the container if it is pixel-based but how do you center a percent-based main container?

#container
{
  width:80%;
  margin:0px auto;
}

That does not center the container :(


The margin property supports percentage values:

margin-left: 10%;
margin-right: 10%;


#container
{
  width:80%;
  position:absolute;
  margin-left:-40%;
  left:50%;
}

or simply

#container
{
  width:80%;
  margin-left:10%;
}


position: absolute;
width: 80%;
left: 0;
right: 0;
margin: 0 auto;


I know it sounds crazy but how about getting the width in jQuery then resetting it so it is a pixel value?

Or basing the width off the page width in jQuery?

It's pretty weird he wants a percent based layout.

Oh and last but not least, two 10% width divs surrounding it ;)


#container { width: 80%; margin: 0 auto; position relative; }

And the element parent of "container" must be position relative or absolute

for example:

body{position:relative;}
#container { width: 80%; margin: 0 auto; position relative; }


Remove the px value in the margin, just like this:

#container { width: 80%; margin: 0 auto; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜