Search code examples
csshtmlhovermousehover

CSS hover element pushes away other divs and layout


Problem: When hover over box1 it should expand without affecting other divs and the document layout but my current code push down the box2 div.

i want box1 to be expend over the box2 without affecting its position.

any help please!

JS Fiddle Demo

<div class = "box1">
    <p>first box</p>
    <ul style="list-style-type:none">
        <li>item 1</li>
        <li>item 2</li>
        <li>item 3</li>
        <li>item 4</li>
    </ul>
</div>
<div class="box2">
    <p>2nd box</p>
</div>

CSS

.box1{
    height: 250px;
    width: 300px;
    background-color: #eee;
    border-radius: 3px;
    border: 1px solid darkgray; 
    position: relative;   
}

.box1:hover{
    height: 400px;
    background-color: white;
    box-shadow: 0 14px 28px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22);
    position: relative;
    z-index: 1;
}

.box2{
    height: 150px;
    width: 400px;
    background-color: #eee;
    border-radius: 3px;
    border: 1px solid darkgray;
    position: relative;
}

Solution

  • Use position: absolute with .box1 in a relative parent

    .wrap {
      position: relative;
      height: 250px;
      width: 300px;
    }
    .box1 {
      position: absolute;
      height: 100%;
      width: 100%;
      background-color: #eee;
      border-radius: 3px;
      border: 1px solid darkgray;
      position: relative;
    }
    
    .box1:hover {
      height: 400px;
      background-color: white;
      box-shadow: 0 14px 28px rgba(0, 0, 0, 0.25), 0 10px 10px rgba(0, 0, 0, 0.22);
      position: relative;
      z-index: 1;
    }
    
    .box2 {
      height: 150px;
      width: 400px;
      background-color: #eee;
      border-radius: 3px;
      border: 1px solid darkgray;
      position: relative;
    }
    <div class="wrap">
      <div class="box1">
        <p>first box</p>
        <ul style="list-style-type:none">
          <li>item 1</li>
          <li>item 2</li>
          <li>item 3</li>
          <li>item 4</li>
        </ul>
      </div>
    </div>
    <div class="box2">
      <p>2nd box</p>
    </div>