如何使叠加效果响应图像

How to make overlay effect responsive with image

您好! 我使上面的图像响应 320x767 像素的屏幕分辨率。我的代码工作正常。

但是,我遇到了一个问题,在图像上创建的阴影效果没有响应。我想要的是随着我的图像变小,阴影也应该随着图像高度变小。或者它应该表现得有反应 我该怎么做?

html

<body>
<div  class=" background-img">
    <img src="img/learning.jpg" class="img-responsive">
    <div class="overlay">
    </div>
    </div>
</body>

Css

.background-img{
    max-width: 100%;
    height: auto;

}

.overlay{
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    background-color: black;
    opacity: 0.5;
}
@media only screen and (min-width:320px) and (max-width:767px){

  .background-img{
        width: 426px !important;
        height: 320px !important ;
    }
    .overlay{
    position:fixed;
    top: 0;
    left: 0;
    width: 30% !important;
    height: 25%!important;
    z-index: 10;
    position: absolute;
    background-color: black;
    opacity: 0.5;
}

因为您在叠加层的高度和宽度中使用了 %

px

中给出固定的高度和宽度
.overlay{
    position:fixed;
    top: 0;
    left: 0;
    width: 100px !important; // set accordinly
    height: 100px !important;// set accordinly
    z-index: 10;
    position: absolute;
    background-color: black;
    opacity: 0.5;
}

width and height declared in % will work according to the height and width of parent. If you don't want the child to change its height and width just define it in px for all screens.

试试这个 CSS:

.background-img {
    max-width: 100%;
    height: auto;
    position: relative;
}

.overlay {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 10;
    background-color: black;
    opacity: 0.5;
}

@media only screen and (min-width:320px) and (max-width:767px) {
    .background-img{
        width: 426px !important;
        height: 320px !important ;
    }
}

我们通常将 z-index 声明应用于弹出窗口 div 使用稍高的值(您使用的是 10),以及位置:相对;导致应用 z-index 值的声明。 如果您按照我的理解方式进行操作,那么这里是代码更改:

 @media only screen and (min-width:320px) and (max-width:767px){

 .background-img{
    position:relative;
    max-width: 100%;
    height: auto;
 }
 .overlay {
   position: relative;
   top: 0;
   left: 0;
   width: 100% !important;
   height: 100% !important;
   z-index: 10;
   background-color:black;
   opacity: 0.5;
}

您可以尝试这段不需要查询就可以响应的代码: https://jsfiddle.net/52ms14gf/1/

.background-img .overlay{
    position: absolute;
    overflow: hidden;
    top: 0;
    left: 0;
}

.background-img .overlay {
    opacity: 1;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 51, 51, 0.5);
}
.container{position:relative;
  }

.container img{width:100%;
 display:block;
 }

我像这样使用 CSS-grid:

.container {
    display: grid;
    grid-template-columns: 1fr;
    grid-template-rows: 1fr;
}

.img-responsive {
    grid-column: 1/2;
    grid-row: 1/2;
    width: 100%;
}

.overlay {
    grid-column: 1/2;
    grid-row: 1/2;
    width: 100%;
}

并且在所有屏幕宽度上都运行良好。