首页 > 解决方案 > 仅使用 CSS 将容器 div 调整为低于内容总宽度时,图像不会调整大小

问题描述

当父 div 变得小于内容宽度的总和时,仅使用 CSS 如何调整图像的大小低于其原始宽度和高度。我有一个带有一些图像的 div,如果我调整窗口的大小可以说低于 400 像素,那么图像的大小不会低于其原始大小。在调整浏览器窗口大小时,有什么方法可以自动调整内容图像。我在下面附上了截断的代码:

.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  max-width: 900px;
  max-height: 256px;
  border: thin solid silver;
}

img {
  height: 100%;
  max-height: 256px;
  width: auto;
}

body {
  margin: 5px;
}
<body>
  <div class="container">
    <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
    <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
    <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
  </div>
</body>

标签: htmlcss

解决方案


您可以使用vw代表 的单位viewport width。因此,假设我们设置为img width屏幕尺寸。33.33vwimg33.33%

body {
  margin: 5px;
}

.container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
  max-width: 900px;
  max-height: 256px;
  border: thin solid silver;
}

img {
  height: 100%;
  width: 33.33vw;
}
<div class="container">
  <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
  <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
  <img src="https://img.icons8.com/pastel-glyph/2x/blood-sample.png" />
</div>


推荐阅读