0
  <div class="main"></div>
   <style>
        .main{ background-color:black;
               position:absolute;
               width:???;
               height:??;
   </style>

如何使 div 居中main并使其高度和宽度几乎为 100%,并且与屏幕的每一侧有 20px 的间隙。

4

7 回答 7

2

默认情况下,块元素的宽度已经是 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%;
}

演示小提琴

于 2012-08-17T11:07:10.023 回答
1

嘿,现在定义这个 css

<style>
   .main{ 
       background-color:black;
       position:absolute;
       margin:20px;
       left:0;
       right:0;
       top:0;
       bottom:0;
    }
</style>
于 2012-08-17T11:12:59.043 回答
0

由于您使用的是绝对定位,您可以试试这个:

<div class="main"></div>

<style>
.main {
background-color: black;
position: absolute;
top: 0;
left: 20px;
right: 20px;
height: 100%;
}
</style>
于 2012-08-17T11:17:34.183 回答
0

这将使div左侧和右侧的 50px 空间居中对齐。

.main {
    margin: 0 50px;  /* [top,bottom] [left,rigth] shorthand syntax */
    width : 100%;
}
于 2012-08-17T11:06:49.090 回答
0

你可以做 :

<style>
   .main{ background-color:black;
          position:absolute;
          width:100%;
          height:100%;
          margin:20px;
 </style>
于 2012-08-17T11:08:15.127 回答
0

您可以使用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 中使用。所以它可能不是最好的解决方案。

http://jsfiddle.net/Kyle_Sevenoaks/wVUat/

于 2012-08-17T11:13:11.850 回答
-1

下面的解决方案如何:

<!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>

请在http://jsfiddle.net/balkon_smoke/yPF8Y/2/找到它

于 2012-08-17T11:17:51.150 回答