CSS 网格图像响应式

问题描述 投票:0回答:1

我正在尝试创建一个小的图像网格。在桌面上,我想要每列 3 个图像,在移动设备上,我想要每列 2 个图像。我这样做没有问题。当我将页面缩小到移动设备尺寸时,问题就开始了。图像顺序正确,但不缩小;它们保持原来的大小,而右边的那个超出了网格(你看不到它的一半)。我尝试了

max-width:100%
width:100 %
等,但没有成功。

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

@media(max-width:768px) {
  .sponsors1 {
    grid-template-columns: 1fr 1fr;
    justify-self: center;
    grid-gap: 8px;
    margin-top: 10px;
    margin-bottom: 20px;
    align-items: center;
    overflow:
  }
  .img1 {
    justify-self: center;
  }
  .img2 {
    justify-self: center;
  }
  .img3 {
    justify-self: center;
  }
}
<div class="sponsors1">
  <a href="#/" class="img1"><img src="images/#.png" alt=""></a>
  <a href="#" class="img2"><img src="images/#.jpg" alt=""></a>
  <a href="#" class="img3"><img src="images/#.png" alt=""></a>
</div>

css responsive-design grid css-grid
1个回答
3
投票

您应该将图像容器的

justify-self
属性设置为
stretch
,然后将图像(而不是其容器)的宽度设置为
100%

        .sponsors1{
            display:grid;
            grid-template-columns: 1fr 1fr 1fr;
        }
        @media(max-width:768px){
            .sponsors1{
                grid-template-columns: 1fr 1fr;
                justify-self:center;
                grid-gap: 8px;
                margin-top: 10px;
                margin-bottom: 20px;
                align-items:center;
                overflow: 
            }
            .img1{
                justify-self: stretch;
            }
            .img2{
                justify-self: stretch;
            }
            .img3{
                justify-self: stretch;
            }
        }
        img {
            width: 100%
        }
<div class="sponsors1">
   <a href="#" class="img1"><img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg" alt=""></a>
   <a href="#" class="img2"><img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg" alt=""></a>
   <a href="#" class="img3"><img src="https://upload.wikimedia.org/wikipedia/commons/8/84/Example.svg" alt=""></a>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.