如何仅在网站布局的一侧无限重复背景颜色/图像并保持内容居中?
最好的方法似乎是使用表格,因为它甚至可以在 IE6 中工作,但是有没有一种方法可以在没有表格和 javascript 的情况下做到这一点,并且至少可以在 IE7+ 中工作?
使用 divs/display:table 的方法在 IE 中根本不起作用,
<style type="text/css">
*{
margin:0;
padding:0;
}
/* table method */
.table-container{
margin-top:20px;
border:0;
border-collapse:collapse;
width:100%;
height:100px;
}
.table-container .left{
background:transparent;
}
.table-container .center{
width:960px;
background:#ddd;
vertical-align:top;
}
.table-container .center div{
margin:0 auto;
width:960px;
}
.table-container .right{
width:auto;
background:#ccc;
}
/* div method */
.div-container{
display:table;
margin-top:20px;
border:0;
width:100%;
height:100px;
}
.div-container .left{
display:table-cell;
background:transparent;
}
.div-container .center{
display:table-cell;
width:960px;
margin:0 auto;
background:#ddd;
vertical-align:top;
}
.div-container .right{
display:table-cell;
width:auto;
background:#ccc;
}
</style>
<table class="table-container">
<tr>
<td class="left"> </td>
<td class="center"><div>Table method : This space must be centered</div></td>
<td class="right"> </td>
</tr>
</table>
<div class="div-container">
<div class="left"> </div>
<div class="center">Div method : This space must be centered</div>
<div class="right"> </div>
</div>
最佳答案
通过使用绝对位置,您可以实现很酷的效果,例如半屏背景颜色。还有比使用 display: table
布局更简单的方法来使文本居中 - 我也在 CSS 中展示了这种布局。
Here is a working examnple on JSFiddle我已尽力在下面的评论中解释 CSS。
这是代码:
CSS
.content {
margin: auto; //use these to center the content
position: relative: //position relative, so the absolute div is positioned relative to this div
text-align: center; //use these to center the content
width: 60%;
}
.content p {
position: relative; //position relative so we can set a z-index
z-index: 1; //z-index is higher than that of the background so it appears above
}
.background {
background-color: #777;
height: 100%;
left:0; //we want the left of the div to be 0px from the left of its container div
position: absolute; //position absolute, so we can put it anywhere we want
top: 0; //we want the top of the div to be 0px from the top of the container div
width: 50%;
z-index: 0; //we want the z-index to be lower than the text
}
HTML
<div class="content">
<p>...text...</p>
<div class="background"></div>
</div>
享受吧
关于css - 背景仅在网站布局的一侧重复,内容居中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6212028/