CSS - 响应图像大小

CSS - Responsive Image Size

我正在尝试让所有图片都具有 max-width: 400px; 并且同时具有响应能力,即移动设备友好。

以下样式确实使图像具有响应性,但是 max-width: 100%; 使图像的大小变化比预期的大很多,因此这不是一个合适的解决方案。

max-width: 100%;
Width: auto;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */

我需要的是这些方面的东西(但响应迅速):

max-width: 400px;
width: auto;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */

我尝试了很多不同的方法,但就是无法正常工作。

感谢您的帮助!

默认情况下,您的图像希望成为父图像的宽度,但您希望将该宽度限制为不超过 400 像素。

max-width: 400px;
width: 100%;
height: auto;
border: 1px #DFDFDF solid; /* Just to make the image look nicer */

为了更深入一点并获得更多控制,您可以将其拆分并使用媒体查询来定位您的移动显示器:

// Desktop
.your-img {
    max-width:400px;
    width:100%;
    height:auto;
    border:1px solid #dfdfdf;
}

// Mobile
@media (max-width:768px) {
    .your-img {
        width:auto;     // Get the original width of the image
        max-width:100%; // So the image can only be as wide as the device max
        display:block;  // Image becomes a block element
        margin:0 auto;  // Centre image if smaller than device width
    }
}