position:absolute,div下的div

时间:2011-12-16 07:56:25

标签: css

我有3个div,每个div都有position: absolute

首先是标题,它的工作。

标题具有恒定高度,第二个div“内容”也有效。

第三个div是“页脚”。

“内容”具有可变高度,当“内容”高于网络浏览器窗口时,“页脚”为“内容”。无论内容高度如何,我都希望“内容”下的“页脚”。

我的标题高度为300px,内容为margin-top: 300px。我不能对页脚使用相同的内容,因为内容没有恒定的高度。

我不想用position: absolute设置一个div,而这3个div放在这个div中。

div#header{
  width: 960px;
  height: 200px;
  left: 50%;
  margin-left: -480px;
  position: absolute;
 }

div#content{
 width: 960px;
 border: 1px solid black;
 left: 50%;
 margin-left: -480px;
 position: absolute;
 margin-top: 200px;
 }

div#footer{
  width: 960px;
  height: 30px;
  left: 50%;
  margin-left: -480px;
  position: absolute;
  bottom: 10px; /*with this i've div fixed to the bottom of web-browsers' window */
  clear: both;
  }

5 个答案:

答案 0 :(得分:3)

你过度定位。

除非你没有分享,否则你不需要绝对定位所有东西。

JSBin Example

答案 1 :(得分:1)

如果你愿意使用 position : relative,在这种情况下position : absolute.header { position : relative; width : 100%; height : 90px; background-color : #000; } .content{ position:relative; width : 100%; min-height : 200px; background-color : #f00; } .footer{ position:relative; width : 100%; height : 50px; background-color : #0f0; } 好一点,http://jsfiddle.net/vFTXg/1/ - 尝试在此处编辑内容高度的值,并自动调整页脚。

<强> CSS

<div class='header'></div>
<div class='content'></div>
<div class='footer'></div>

<强> HTML

{{1}}

答案 2 :(得分:0)

我建议使用CSS浮动

做这样的事情:

<div id="wrapper">
    <div id="header">...</div>
    <div id="content">...</div>
    <div id="footer">...</div>
    <div class="clear"></div>
</div>

在包装器上设置网站宽度,让其他div具有相同的宽度。

在标题,内容和页脚

上使用 float:left

在clear-div上设置清除:两者

现在你可以在想要拥有固定高度的元素上设置高度 - 而且你不必为绝对定位而烦恼。如果你坚持使用定位,你可以放置包装器。

答案 3 :(得分:0)

将来浏览器可以计算出来。对于您的示例,如果内容高度较低,则可以很好地计算内容的最小高度以将foorter设置为底部,如果内容具有高值,则在内容之后设置页脚。 E.g:

HTML:

<div id="header" class="content">header</div>
<div id="content" class="content">content</div>
<div id="footer" class="content">footer</div>

CSS:

html, body {
    height: 100%;
}
.content {
    position: relative;
    width: 960px;
}
#header {
    height: 200px;
}
#content {
    border: 1px solid black;
    min-height: -moz-calc(100% - 302px);
    min-height: -webkit-calc(100% - 302px);
    min-height: calc(100% - 302px);
}
#footer {
    height: 100px;
}

不幸的是目前只有firefox和IE9及更高版本支持calc,所以这在理论上更为明确。如果您想测试它,请参阅此jsfiddle 如果您想对所有当前浏览器执行此操作,则需要使用javascript。

答案 4 :(得分:0)

如果您希望某些内容具有恒定的宽度并居中,请尝试使用

#footer,
#header,
#footer {
    width: 960px;
    margin: 0 auto;
}

忘了

left: 50%;
margin-left: -480px;
position: absolute;
相关问题