首页 > 解决方案 > 使用媒体查询的 CSS 图像大小

问题描述

嘿,我一直在尝试为我开发的网站创建媒体查询。我遇到了一个问题,当我在媒体查询中调整图像大小时,它会调整边框,但是完整的图像大小保持不变。此链接中显示的示例。

对于该页面上的第一张图片,我已将这些 CSS 属性用于媒体查询。

#working {
        float: left;
        margin: 0px auto;
        border: 2px solid #000000;
        width: 175px; 
        height: 175px;
        display: block;
}

对于非媒体查询,我使用了这个 CSS 代码:

#working {
    float: right;
    margin: 10px 215px 10px 110px;
    border: 2px solid #000000;
    width: 350px; 
    height: 350px;
    display: block;
}

标签: htmlcssmedia-queriesimage-resizing

解决方案


解决你的问题很简单。要使图像正确调整,请执行以下操作。

  1. 将图像包装为 div 或 HTML5 图形(将溢出属性值设置为隐藏)
  2. 将图像设置为始终适合包装器
  3. 图像高度或宽度应为 100%,而另一个为自动
  4. 在所需的断点处调整图像包装器

注意:我认为您的问题的原因是图像重叠。

  • 在全窗口模式下运行代码片段,然后调整窗口宽度以查看运行中的代码。

#image-wrapper {
width: 300px;
height: 300px;
overflow: hidden; /* Hide overlapping part of the imager */
border: 5px solid red; /* Just show that the image is controled */
transition: all .7s; /* Just to make the adjustment smooth */
}

#image-wrapper img {
width: 100%;
height: auto; /* Allows the image to adjust properly */
transition: all .7s;
}


/* Now see what happens when the device or screen is less that 601px */

@media only screen and (max-width: 601px) {

#image-wrapper {
width: 150px;
height: 150px;
margin: auto; /* This should position it in the center */
transition: all .7s;
}

}
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">   
<div id="image-wrapper">
<img src="https://i.stack.imgur.com/71WkH.jpg" />
</div>


推荐阅读