2012-03-17 162 views
7

我想將div對齊到頁面底部,而不是屏幕底部。當我這樣做:如何將div對齊到頁面底部,而不是屏幕底部

#contact-block{ 
position: absolute; 
    bottom: 0; left: 0; 
} 

,該div被放置在屏幕的底部區域。當我的頁面很長時,我必須向下滾動,應該在底部的div浮在中間的某個位置。

可能有一個簡單的解決方案,但我只是沒有看到它。

這裏是我的HTML:

<div id="left"> 
<div id="submenu"> <span class="menutitle">Services</span> 
    <ul> 
    </ul> 
</div> 

<div id="contact-block"> 
<span class="contacttitle">Contact</span></div> 
</div> 
<div id="content"> 
</div> 

我還添加了一個小圖像說明我的意思: enter image description here

紅格是接觸股利。

編輯: 我找到了jQuery和CSS的解決方案。這可能不是最好的解決方案,但嘿,它的工作原理。

的jQuery:

var offset= $(document).height()-$("#contact-block").height()- $("#footer").height()-60; 
$("#contact-block").css("top", offset); 
$("#contact-block").css("left", $("#wrapper").position().left); 

CSS:

#contact-block { 
position : absolute; 
width:216px; 
height:100px; 
background:url(../img/contact-bg.jpg) repeat-x #5c5c5c; 
} 
+1

那麼,你爲什麼不把它放在HTML的底部? – SergeS 2012-03-17 13:15:47

+1

你能發佈你的html嗎? – 2012-03-17 13:15:56

+0

它是菜單下方菜單下方的內容左側的塊。菜單對齊到頂部,觸點塊應該對齊到底部。 – samn 2012-03-17 13:17:35

回答

1

absolute定位元素的位置取決於始祖元素,這是不定位static(這是默認的,所以您必須明確將其設置爲relative(或absolute))。

因此,請確定您的封閉容器有100%的文件高度和position:relative,並且一切正常。

0

您可能想看看等高欄:http://css-tricks.com/fluid-width-equal-height-columns/

在簡單的情況下,這可能是足夠的(我假設你#left列彩車左,content列浮動權,也沒有其他的包裝元素,只是body):

body { 
    position:relative; 
} 

#contact-block { 
    position:absolute; 
    bottom:0; 
    left:0; 
} 

不要忘了將更清晰的元素<div style="clear:both"></div>添加到您的body的底部。

2

你可以絕對定位你的div。這項技術需要一個#wrapper元素,我不是一個粉絲,但嘿,你必須做watcha必須做的。

在此示例中,我完全刪除了#leftdiv,因爲它僅用於佈局目的並且不再需要。

HTML:

<div id="wrapper"> 
    <div id="submenu">This is services</div> 
    <div id="contact-block">This is contact</div> 
    <div id="content">This is content</div> 
</div>​ 

CSS:

#wrapper { 
    position: relative; 
    width: 960px; 
} 

#submenu { 
    position: absolute; 
    left: 0; 
    top: 0; 
    width: 320px; 
    height: 320px; 
} 

#contact-block { 
    position: absolute; 
    left: 0; 
    bottom: 0; 
    width: 320px; 
    height: 160px; 
} 

#content { 
    position: relative; 
    left: 320px; 
    right: 0; 
    top: 0; 
    width: 640px; 
    height: 640px; 
} 

//#content position is relative for the #wrapper to stretch. 
//The left property is equal to the width of the #submenu or #contact-block element 

好點這一技術的是,它可以讓你更清潔的HTML。如果需要,我相信製作一個移動版本的版本會更容易。

The jsfiddle

其他的想法:#wrapper元素可以很容易地支持您刪除body元素,這是邁向語義HTML的一大步。 Check this out!

+0

我試圖使用body作爲包裝元素 - 我沒有意識到的是,因爲我的內容比我需要的位置大:相對於身體或默認情況下,絕對定位的元素是相對於窗口! – Mark 2013-07-04 02:26:08

0

我會建議把紅色的div放在正確的長格里面,並在結尾。然後使用position: relative和紅色div上的負左邊距將其推出左邊。這樣,隨着右側div的擴展,您的紅色div始終停留在底部。