Html 居中基于百分比的 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2624159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:41:56  来源:igfitidea点击:

Centering a percent-based div

csshtml

提问by Sarfraz

Recently, a client asked that his site be percent-based rather than pixel-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?

最近,一位客户要求他的网站基于百分比而不是基于像素。百分比将设置为 80%。如你们所知,如果容器是基于像素的,那么将容器居中是很容易的,但是如何将基于百分比的主容器居中呢?

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

That does not center the container :(

这不会使容器居中:(

回答by David

The margin property supports percentage values:

margin 属性支持百分比值:

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

回答by oezi

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

or simply

或者干脆

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

回答by Adirael

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

去掉margin中的px值,就像这样:

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

回答by joanballester

#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; }

回答by Lele Carabina

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

回答by Kyle Hotchkiss

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

我知道这听起来很疯狂,但是如何在 jQuery 中获取宽度然后将其重置为像素值呢?

Or basing the width off the page width in jQuery?

或者基于jQuery中的页面宽度设置宽度?

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

他想要一个基于百分比的布局,这很奇怪。

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

哦,最后但并非最不重要的是,它周围有两个 10% 宽度的 div ;)