<div class="main"></div>
<style>
.main{ background-color:black;
position:absolute;
width:???;
height:??;
</style>
如何使 div 居中main
并使其高度和宽度几乎为 100%,并且与屏幕的每一侧有 20px 的间隙。
默认情况下,块元素的宽度已经是 100%。
您需要做的就是添加填充或边距来创建您的“间隙”。
<style>
.main{ background-color:black;
position:absolute;
margin: 0 20px;
height:100%;
}
</style>
我错过了你的绝对定位。
使用绝对定位,我会使用这个:
#main {
background: #a00;
position: absolute;
top: 0;
left: 50px;
right: 50px;
height: 100%;
}
嘿,现在定义这个 css
<style>
.main{
background-color:black;
position:absolute;
margin:20px;
left:0;
right:0;
top:0;
bottom:0;
}
</style>
由于您使用的是绝对定位,您可以试试这个:
<div class="main"></div>
<style>
.main {
background-color: black;
position: absolute;
top: 0;
left: 20px;
right: 20px;
height: 100%;
}
</style>
这将使div
左侧和右侧的 50px 空间居中对齐。
.main {
margin: 0 50px; /* [top,bottom] [left,rigth] shorthand syntax */
width : 100%;
}
你可以做 :
<style>
.main{ background-color:black;
position:absolute;
width:100%;
height:100%;
margin:20px;
</style>
您可以使用calc()
CSS3 中的新属性:
.main
{
margin: 0 auto;
background-color:black;
color: #fff;
position:absolute;
width: -webkit-calc(100% - 20px);
height: -webkit-calc(100% - 20px); /*repeat with other browsers codes*/
}
这告诉 div 为 100% 宽/高,但删除 20px,同时将其保持在中心。
IT 可以在 IE9(不低于)m Firefox 4.0、Chrome 19 和 Safari 6 中使用。所以它可能不是最好的解决方案。
下面的解决方案如何:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<style>
#mask {
background-color: rgba(0, 0, 0, .5);
opacity: 0.5;
position: absolute;
top: 20px;
left: 20px;
right: 20px;
bottom: 20px;
}
</style>
</head>
<body>
<div id="mask" />
</body>
</html>