How to make a fade-in effect in a div behind another div, without the former overlapping the latter?

Issue

During the fade-in animation, the blue div is overlapping the red one, even though the red div has "position: absolute". How can I make it so the red one is on top also during the blue div’s fade-in animation (preferably using only css, if it’s not possible, with vanilla javascript instead)?

Live demo: https://jsfiddle.net/s5yvoL4z/2/#&togetherjs=4c97JQOdcD

Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .a {
            background-color: red;
            width: 15em;
            height: 15em;
            position: absolute;
            margin-top: -5rem;
        }

        .b {
            background-color: blue;
            width: 15em;
            height: 15em;
            margin-top: 5rem;
            animation: show-img 1s;
        }

        @keyframes show-img
        { from { opacity: 0 }
        to {opacity: 1}
        }

    </style>
</head>
<body>
    <div class="a"></div>
    <div class="b"></div>
</body>
</html>

Solution

Add z-index: 1 to your .a class and for cleanliness add z-index: 0 to your .b class. The position attribute affects the positioning of the element but not the order in which they are stacked.

        .a {
          background-color: red;
          width: 15em;
          height: 15em;
          position: absolute;
          margin-top: -5rem;
          z-index: 1;
        }

        .b {
          background-color: blue;
          width: 15em;
          height: 15em;
          margin-top: 5rem;
          animation: show-img 1s;
                    z-index: 0;
        }

        @keyframes show-img {
          from {
            opacity: 0;
          }

          to {
            opacity: 1;
          }
        }
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="a"></div>
    <div class="b"></div>
</body>
</html>

Answered By – AStombaugh

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.