2011-05-25 123 views
0

雖然只有一個。元素高度與其他元素高度相同,但寬度和絕對位置相同

我有下面的代碼將div作爲背景的一部分。如果用戶的屏幕分辨率= 1024px,則滾動不會顯示。

問題是我需要#background div與#content的高度相同。

有沒有什麼辦法可以達到這個效果只有css

<body> 
    <style> 
     body { 
      margin:0px; 
      background: yellow; 
     } 
     #background { 
      overflow: hidden; 
      position: absolute; 
      z-index: -1; 
      width: 100%; 
      height: 100%; /* ??? */ 
     } 
     #background > div { 
     background: blue; 
      margin: auto; 
      width: 1108px; 
      height: 100%; 
      z-index: -1; 
     } 
     #content { 
      background: red; 
      width: 1004px; 
      margin: auto; 
     } 
    </style> 
    <div id="background"><div><!-- this will not affect page scrolling if its width id greater than browsers window --></div></div> 
    <div id="content"> 
     lorem ipsum dolor sit amet<br /> 
      [...] 
    </div> 
</body> 



編輯:

感謝downvotes和評論。我自己找到答案。所有你需要的是包裹everithing與<div style="position: relative">



EDIT2:

或乾脆放棄position: relative<body>

回答

1

好吧,我介紹id="parent"股利和使這個jsFiddle,然後我加top:0bottom:0#background DIV的高度調整到#parent股利。

我也改變了例如小提琴的寬度,這樣可以看到工作:

<body> 
    <style> 
    body { 
     margin:0px; 
     background: yellow; 
    } 
    #parent{ 
     position:relative; 
    } 
    #background { 
     background-color:black; 
     overflow: hidden; 
     position: absolute; 
     z-index: -1; 
     top:0; 
     bottom:0; 
    } 
    #background > div { 
     margin: auto; 
     width: 1108px; 
     height: 100%; 
    } 
    #content { 
     background: red; 
     width: 1004px; 
     margin: auto; 
    } 
    </style> 
    <div id="parent"> 
     <div id="background"> 
      <div><!-- this will not affect page scrolling if its width id greater than browsers window --> 
      </div> 
     </div> 
     <div id="content"> 
      lorem ipsum dolor sit amet<br /> 
      [...] 
     </div> 
    </div> 
</body> 

這是你達到了嗎?

+0

對不起。不接受。我首先想到了它。你不需要底部:0;頂部:0;使其工作。 – seler 2011-05-25 18:00:11

+1

@seler對不起seler,但是你需要把代碼放在代碼中,否則,當你在'#background'裏放置更多的代碼時,它的高度會增加! (先測試解決方案!!) – 2011-05-25 18:04:54

+0

@Nacho對不起,我不需要'#background'中的任何內容,這就是爲什麼它被命名爲_background_。我測試你的解決方案。添加頂部:0;底部:0;什麼都不變。 – seler 2011-05-25 18:14:24

0

報價OP:問題是我需要#background div與#content高度相同。

如果您希望#background始終與#content的高度相同,只需將#content div放入#background div內。