Mati
Mati

Reputation: 781

CSS z-index with position absolute

I have simple code

The problem is the red div. It is animated but it have z-index bigger than it parent so while animating it overshadowing the main div. I can solve this problem when i give to animated div z-index: -1 but :hover doesn't work properly (animated div disappears). Anyone can help?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
    .main {
        width: 100px;
        height: 100px;
        background: green;
        position: relative;
    }

    .main .bar {
        height: inherit;
        width: 300px;
        position: absolute;
        background: red;
        left: -300px;
    }

    .main:hover .bar {
        left: 100px;
        transition: left .3s;
    }
</style>
</head>
<body>
    <div class="main"><div class="bar"></div></div>
</body>
</html>

https://jsfiddle.net/24qbyh4p/

Upvotes: 2

Views: 1046

Answers (1)

Oriol
Oriol

Reputation: 288710

The solution is wrapping the contents of .main in an inner container with a z-index greater than .bar's one.

.main {
  width: 100px;
  height: 100px;
  position: relative;
}
.main > .bar {
  height: inherit;
  width: 300px;
  position: absolute;
  background: red;
  left: -300px;
}
.main > .content {
  height: 100%;
  background: green;
  position: relative;
  z-index: 1;
}
.main:hover .bar {
  left: 100px;
  transition: left .3s;
}
<div class="main">
  <div class="bar"></div>
  <div class="content"></div>
</div>

Upvotes: 2

Related Questions