【问题标题】:Preventing relatively positioned div from pushing down content防止相对定位的div下推内容
【发布时间】:2012-11-08 20:09:38
【问题描述】:

如何防止相对定位的 div 下推后面的内容?在下面的示例中,我试图在较大的红色 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>

【问题讨论】:

    标签: html css


    【解决方案1】:

    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,从而导致您在示例中看到的闪烁。

    【讨论】:

      【解决方案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>
      

      【讨论】:

        猜你喜欢
        • 2012-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-29
        • 2019-02-18
        • 1970-01-01
        相关资源
        最近更新 更多