防止相对定位的div推倒内容

时间:2012-11-08 20:09:39

标签: html css

如何阻止相对定位的div推送下面的内容?在下面的示例中,我尝试在较大的红色顶部上显示一个小的绿色div,但是当绿色div出现时,下一个红色div会被按下。

如果有更好的方法,我会很感激提示。

以下是一个正在运行的示例:http://jsfiddle.net/38Rqh/

<html>
<head>
<style type="text/css" media="screen">

.top {
  display: none;
  background-color: green;
  width: 100px;
  position: relative;
  top: -50px;
}

.bottom {
  width: 200px;
  height: 200px;
  background-color: red;
  border: 1px solid black;
}

.bottom:hover + div {
    display: block;
}

</style>
</head>
<body>

<div class="bottom">

</div>
<div class="top">Displaying data</div>

<div class="bottom">

</div>
<div class="top">Displaying data</div>

<div class="bottom">

</div>
<div class="top">Displaying data</div>

</body>
</html>

2 个答案:

答案 0 :(得分:6)

relative仍占用空间。你需要的是absolute。一种可能性是将.bottom元素设置为position: relative,然后将.top元素放在其中并绝对定位。

http://jsfiddle.net/38Rqh/1/

.top {
  display: none;
  background-color: green;
  width: 100px;
  position: absolute;
  top: 150px;
}

.bottom {
  width: 200px;
  height: 200px;
  background-color: red;
  border: 1px solid black;
    position: relative;
}

.bottom:hover .top {
    display: block;
}
<div class="bottom">
<div class="top">Displaying data</div>
</div>

<div class="bottom">
<div class="top">Displaying data</div>
</div>

通过这种方式,.top元素的位置将与其包含的.bottom相对应。

这样做的另一个好处是,当悬停在.top上时,不会隐藏.top,从而导致您在示例中看到的闪烁。

答案 1 :(得分:2)

我可能把它与应该出现的地方混在一起,但是使用包装div和绝对位置而不是相对将会消除额外的空间。

<html>
<head>
<style type="text/css" media="screen">

.top {
  display: none;
  background-color: green;
  width: 100px;
  position: absolute;
  bottom: 50px;
}

.bottom {
  width: 200px;
  height: 200px;
  background-color: red;
  border: 1px solid black;
}

.bottom:hover + .top {
    display: block;
}

.wrapper { position: relative; }

</style>
</head>
<body>

<div class="wrapper">
  <div class="bottom">

  </div>
  <div class="top">Displaying data</div>
</div>
<div class="wrapper">
  <div class="bottom">

  </div>
  <div class="top">Displaying data</div>
</div>
<div class="wrapper">
  <div class="bottom">

  </div>
  <div class="top">Displaying data</div>
</div>
</body>
</html>
相关问题