简体   繁体   中英

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

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>

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>

.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;}
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM