-->

Using CSS position absolute, relative and z-index

2020-07-31 03:16发布

问题:

I am trying to overlay 2 images but they both need to be responsive in height and size (i.e. the parent DIV is not a fixed size (specifically a play button over a thumbnail).

Example...

<div class="img-wrap">
   <div class="play-button">Play Button Img</div>
   <div class="thumb-image">Thumbnail Video Image</div>
</div>

Normally I would set height, width and position relative on .img-wrap and then set position absolute and z-index of .play-button and .thumb-image to allow the play button image to sit nicely over the thumbnail.

The problem I have is the thumbnail is responsive so I am unable to set the height and width of .img-wrap. I can still sett he z-index OK but without setting a height everything below is despairing underneath it.

Is there is a fix to this?

回答1:

Use the following technique:

<!doctype html>
<html>
<head>
<title>Responsive Nested Images</title>
<meta charset="utf-8">
</head>
<style>
     .play-button, .thumb-image
       {
       position: absolute; /* Absolutely position both containers */
       font-size:0; /* Hide text */
       line-height:0;
       }
     .play-button { outline: 1px solid red; } /* Add outline for debugging */
     .thumb-image { top:50%; left: 50%; outline: 1px solid green; } /* Responsive Container */
     .play-button img, .thumg-image img { max-width: 100%; height: auto; } /* Responsive Image Dimensions */
</style>
</head>
<body>
    <div class="play-button"><img src="http://www.stackoverflow.com/favicon.ico">
      <div class="thumb-image">Thumbnail Video Image<img src="http://www.stackoverflow.com/favicon.ico"></div>
      Play Button Img
    </div>
</body>
</html>

References

  • Fit-and-shrink technique
  • PlayBox: Vertical and Horizontally Centered Modal