2015-12-02 33 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