css div定位问题

时间:2010-05-06 02:37:28

标签: css html

我有以下css的三个div:

div#container {
  width: 780px;
}
div#photos {
  width: 780px;
  height: 300px;
}
div#content {
  position: relative;
  top: -106px;
  width: 780px;
}


<div id="container">
  <div id="photos">photos are here</div>
  <div id="content">content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer content goes here, but sits slightly on top of the photos layer</div>
</div>

我的问题是,因为我已经将内容层设置为顶部:-106px,当我想要“容器”div在“内容”div之后立即结束时,存在一个很大的差距。我尝试在“容器”div上设置margin-bottom:-106px,但这并没有改变“容器”div的高度。

“内容”div的高度会有所不同,因为它显然适用于文本等。有什么方法可以使这个工作吗?

提前致谢:)

5 个答案:

答案 0 :(得分:1)

将容器div上的高度设置为100%可能有所帮助。您可以尝试的另一件事是在容器div上设置overflow属性。溢出:隐藏或溢出:自动两者都会使你的容器div'包裹'你的其他div更好。

请记住,浏览器的里程会有所不同。

答案 1 :(得分:1)

间隙的原因是相对定位不会移除最初为该元素创建的空间,即使您移动它也是如此。尝试将其更改为“绝对”,看看是否符合您的要求。

答案 2 :(得分:1)

尝试将CS​​S更改为

div#container {
width: 780px;
position:relative;  <---------------
}
div#photos {
width: 780px;
height: 300px;
background: #aaaaaa;
}
div#content {
  position:absolute; <------------
  top: 106px;        <------------
  width: 780px;

}

答案 3 :(得分:1)

我建议使用不同的方法,绝对定位你的图像,然后在容器上用上边距(或填充,如果你需要背景)推下内容。

div#container {
  width: 780px;
  margin-top:106px;
}
div#photos {
  width: 780px;
  height: 300px;
  position:absolute;
  top:0;
  z-index:50;
}
div#content {
  position: relative;
  width: 780px;
  z-index:100;
}

答案 4 :(得分:1)

您可以通过设置否定position: relative来实现相同的效果,而不是使用top并设置margin-top

div#content {
  margin-top: -106px;
  width: 780px;
}