将div放在页面中间的问题

时间:2014-07-24 04:00:47

标签: html css

在有人将此标记为副本之前,我已经在此搜索过,而没有找到一个非常适合我需要做的解决方案。

这是我的fiddle

以下是html的代码..

<div class="top-background"></div>
<div class="center-content"></div>
<div class="bottom-background"></div>

这是CSS样式表......

body {
margin: 0;
padding:0;
}
.top-background {
background-color:black;
width:100%;
height:50%;
position:absolute;
top:0;
left:0;
}
.bottom-background {
background-color:white;
width:100%;
height:50%;
position:absolute;
bottom:0;
}
.center-content {
background-color:yellow; 
width:250px; 
height:120px;
margin: auto;
position:relative;
}

我可以使用top:300px将中心内容div移向中心。但这取决于屏幕尺寸,这不会有任何好处。

中心内容div中会有一个图形(它不会显示为黄色背景),图形与我所拥有的颜色相反。我可能已经在文本对齐中心的身体中完成了这个,但是我放入的所有内容都将对齐中心(并且它不会很漂亮)并且使用了一个表格。

2 个答案:

答案 0 :(得分:2)

这样做可以为类center-content提供一些css属性就足够了。

.center-content {
background-color:yellow; 
width:250px; 
height:120px;
margin: auto;
position:relative;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -125px;
}

请参阅此小提琴http://jsfiddle.net/Cwm76/sscuL/

答案 1 :(得分:1)

申请:

.center-content {
background-color:yellow; 
width:250px; 
height:120px;
margin: auto;
position:absolute;
top: 50%;
left: 50%;
margin-top: -60px; /* half of the height */
margin-left: -125px; /* half of the width */
}