user1810414
user1810414

Reputation: 113

Preventing relatively positioned div from pushing down content

How can I prevent relatively positioned div from pushing down content that follows? In following example I am trying to display a small green div on top of a bigger red one but the next red div gets pushed down when the green div appears.

If there is a better way of doing this, I'd appreciate tips.

Here is a running example: 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>

Upvotes: 8

Views: 11811

Answers (2)

James Montagne
James Montagne

Reputation: 78650

relative still takes up space. What you need is absolute. One possibility is to set your .bottom elements to position: relative and then place the .top elements within them and position them absolutely.

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>

In this way, the .top elements will be positioned in relation to their containing .bottom.

This has the added benefit of not hiding the .top when hovering on the .top itself, causing the flicker you see in your example.

Upvotes: 7

gotohales
gotohales

Reputation: 3695

I may have mixed this up with what should be appearing where, but using wrapper divs and position absolute instead of relative will get rid of the extra space.

<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>

Upvotes: 2

Related Questions