Search code examples
csshoverpositionz-index

How to get a div with z-index to overlay another div on hover


I have a container div with several smaller div:s inside, all of them with float:left;. If I hover one of the smaller div:s the height and width should be increased and it should overlay the other div:s without moving them.

HTML:

 <div id="boxcontainer">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
 </div>

CSS:

.box {
  float:left;
  position: relative;
  width:150px;
  height:150px;
  margin:5px;
  background-color: yellow;
}

#boxcontainer {
  position: relative;
  width:500px;
  height:auto;
}

.box:hover {
  z-index:100;
  width:300px;
  height:auto;
}

How can I achieve this?


Solution

  • z-index only works on positioned elements (position:absolute, position:relative, or position:fixed).

    Instead of float left try position absolute.

    I have added a container around each box and positioned each element absolutely within it. This way you can add as many boxes as you wish and keep the same class.

    EXAMPLE

    HTML

    <div id="boxcontainer">
        <div class="box">
            <div class="Inside"></div> 
        </div>         
        <div class="box">
            <div class="Inside"></div> 
        </div>         
        <div class="box">
            <div class="Inside"></div> 
        </div>     
    </div>
    

    CSS

    #boxcontainer{
        position: relative;
        width:500px;
        height:500px;
    }
    .box{
        position:relative;
        float:left;
        width:150px;
        height:150px;
        margin:5px;
    }
    .Inside{    
        background:green;
        position:absolute;
        top:0;
        left:0;
        width:150px;
        height:150px;
        transition:all 0.5s ease-in-out;
        -webkit-transition:all 0.2s ease-in-out;
    }
    .Inside:hover{
        z-index:100;
        width:250px;
        height:250px;
        background:#666666;
    }
    

    http://jsfiddle.net/JJ3v4/3/