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

Time:04-20

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 ></div>
    <div ></div>
</body>
</html>

CodePudding user response:

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 ></div>
    <div ></div>
</body>
</html>

CodePudding user response:

.a {
    background-color: red;
    z-index: 1;
    width: 15em;
    height: 15em;
    position: absolute;
    animation: show-img 2s;
}

.b {
    background-color: blue;
    position: absolute;
    width: 15em;
    height: 15em;
}

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

CodePudding user response:

This can be achieved by adding z-index: 1; to the .a.

  • Related