2015-12-02 32 views
0

HTML绝对100%的宽度DIV溢出一面

<header> 
    <div class="container"> 
     <div class="parent"> 
      <div class="child"></div> 
     </div> 
    </div> 
</header> 

CSS

header .parent{ 
      text-align:left; 
      position: absolute; 
      z-index: 2; 
      margin-top: 15%; 
     } 
header .parent .child{ 
       /*Nothing here yet*/   
     } 

我想.parent是这样 enter image description here 当我设置.parentwidth:100%,我有这个 enter image description here

的左侧是正确的,但其他的溢出
我不想上使用position: relative.container因为.parent将由其他的div外头覆盖,即使我试图用z-index
有什么问题吗?有谁能够帮助我 ?

回答

1

您需要为绝对定位的元素设置两个或多个偏移量(topleftright, bottom)。

在下面的例子中,我创建了一个header,其边框高度为100px,包含.container,高度为一半,边距为20px。

例如,如果要使.parent的左右边缘与.container的边缘重合,请将左右偏移设置为20px。

您可以通过将值分配给top来控制垂直位置。

如果您未指定偏移值,则它们会默认为与常规内容流中的元素位置对应的值。

在你原来的例子中,.parent左边缘往往对应于.container左侧边缘,因为.parent左边缘将开始在.container左边缘,然后如果你设置了width: 100%,这将迫使右边缘对应于默认左边缘的的窗口宽度的100%,这导致溢出。

要完全理解这里发生了什么,你需要阅读CSS规范有关绝对定位,即:

http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

尤其是包含块静态位置的概念。

body { margin: 0;} 
 
header .parent { 
 
    border: 1px dashed red; 
 
    position: absolute; 
 
    height: 50%; 
 
    top: 120px; 
 
    left: 20px; 
 
    right: 20px; 
 
} 
 

 
header { border: 1px solid black; height: 100px; } 
 
.container { border: 1px dotted blue; height: 50%; margin: 20px;}
<header> 
 
    <div class="container"> 
 
    <div class="parent"> 
 
     <div class="child"></div> 
 
    </div> 
 
    </div> 
 
</header>

+0

谢谢你我这样的工作,但只有当你知道的'填充。容器“将值放在'left'和'right'上 – user3761386

+0

所以你希望'.parent'的宽度与'.container'的宽度相同吗? “.container”的宽度由“.header”的宽度(考虑填充,边距,边框)决定。你可以说得更详细点吗? –

0

.container类需要的位置是:相对的。当你还没有相对容器设置绝对DIV,它正在考虑车身宽度

.container { 
    position: relative; 
} 
+0

对不起,我没有提及'.parent'将会被其他'header'之外的div覆盖,如果我这样做的话。我试图用z-index来启动它,但不起作用 – user3761386