Html 如何使用 CSS 将两列居中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14814745/
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
How to center two columns using CSS?
提问by Fastkowy
I'm trying to center two columns on my website but there are some problems. The result of every change is left position (see picture). What am I doing wrong? Here's my CSS:
我试图在我的网站上居中放置两列,但存在一些问题。每一个变化的结果是左侧位置(见图片)。我究竟做错了什么?这是我的 CSS:
body {
background - image: url("../img/gray.png");
}
#header {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 100px;
background: #cc0000;
text - align: center;
}
#wrapper {
margin: 100px;
width: 1280px;
}
#leftcolumn {
float: left;
background - image: url("../img/gray.png");
margin: 10px 0px 10px 0px;
padding: 10px;
height: 682px;
width: 460px;
}
#rightcolumn {
float: left;
color: #333;
border: 1px solid # ccc;
background: #F2F2E6;
margin: 10px 0px 10px 0px;
padding: 10px;
height: 500px;
width: 439px;
display: inline;
position: relative;
}
Thanks
谢谢
回答by BenM
Since the two columns' width is less than the width of the wrapper (i.e. 959px vs 1280px), you'll need to place the two columns inside a fixed width container:
由于两列的宽度小于包装器的宽度(即 959px 与 1280px),您需要将两列放在一个固定宽度的容器中:
<div id="wrapper">
<div id="column_container">
<div id="column1"></div>
<div id="column2"></div>
</div>
</div>
And then do something like:
然后执行以下操作:
#column_container {
width: 959px;
margin: 0 auto;
}
回答by gotohales
Without seeing it live, something like this should work:
没有看到它的现场,这样的事情应该工作:
#wrapper {
width: 1280px;
margin:100px auto ;
}
But as has been mentioned, this will only center #wrapper
. The columns don't fill the entire 1280 width so they are still left aligned in #wrapper
.
但正如已经提到的,这只会居中#wrapper
。列不会填满整个 1280 宽度,因此它们仍然在#wrapper
.