如何将div对齐到页面底部而不是屏幕底部

9

我想将一个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 红色div是联系人div。
编辑:我已经用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
它是内容左侧的一个块,在菜单下方,与菜单在同一div中。菜单对齐顶部,联系块应对齐底部。 - samn
正确地回答这个问题需要你的HTML + CSS知识,但我猜你把这个元素相对于某个不应该的对象进行了定位。 - mikevoermans
为什么不与其他人分享你的答案? - dan
你是什么意思?我已经在我的问题中编辑了我的答案。 - samn
3个回答

2
你可以将你的
元素绝对定位。这种技术需要一个#包装器元素,我不太喜欢它,但是嘿,你必须做你必须做的事情。
在这个例子中,我完全删除了#left
,因为它只用于布局目的,现在不再需要。
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代码。如果需要,我相信制作移动版本会更容易。
这是jsfiddle链接。
另外,可以轻松删除#wrapper元素,使用body元素代替,这是向语义化HTML迈出的重要一步。请查看这个链接!

我一直在尝试将body用作包装元素 - 我没有意识到的是,因为我的内容比窗口更大,所以我需要在body上使用position:relative,否则默认情况下绝对定位的元素相对于窗口! - Mark

2
你的 absolute 定位元素的位置取决于第一个非 static 定位的祖先元素(这是默认设置,所以你必须将其显式设置为 relative(或 absolute))。
因此,请确保你的封闭容器 #left 具有 100% 的文档高度和 position:relative,然后一切都会很好。

0
我建议将红色的 div 放在右边的长 div 内部并放在其末尾。然后使用 position: relative 和红色 div 上的负左边距将其推向左侧。这样,随着右侧 div 的扩展,红色 div 总是保持在其底部。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接