【问题标题】:Img doesn't respect width in html (with flexbox)Img 不尊重 html 中的宽度(使用 flexbox)
【发布时间】:2021-11-09 06:47:05
【问题描述】:

我有一些 html 应该在顶部创建一个图像,在下面创建一个图片库。

<!DOCTYPE html>
<html lang="en">
<head>
  <title>your page title goes here</title>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="stylesheet" href="index.css" />
</head>
<body>
  <div class="container">
    <h1>My Photo Gallery</h1>
    <div class="gallery">
      <figure>
        <img src="img/dog1.jpeg" alt="first dog">
        <figcaption>Example Photo</figcaption>
      </figure>
      <div class="img-bar">
        <img src="img/dog2.jpeg" alt="second dog"/>
        <img src="img/dog3.jpeg" alt="third dog"/>
        <img src="img/dog4.jpeg" alt="fourth dog"/>
        <img src="img/dog5.jpeg" alt="fifth dog"/>
      </div>
    </div>
  </div>
</body>
</html>

为了设置图片库的样式,我添加了以下样式:

.img-bar{
  display: flex;
}

img {
  width: 100%;
}

.img-bar img {
  object-fit: cover;
  width: 300px;
  height: 300px;
}

所有图像文件的尺寸均 > 300 像素 x 300 像素,因此我希望它们遵循 CSS 规则。但是,正如您从下面的照片中看到的那样,第二张图片不符合规则(它的高度大于宽度)。作为参考,该图像文件的实际尺寸为 934 像素 x 1401 像素。

任何帮助将不胜感激!谢谢。

【问题讨论】:

  • 将 flex-shrink:0 添加到您的图像中

标签: html css flexbox width


【解决方案1】:

您想设置容器的尺寸,然后让里面的图像展开以填充它。我会像这样重新洗牌:

img {
  width: 100%;
  height: 100%;
  object-fit:cover;
}

.img-bar {
  display:flex;
  width: 300px;
  height: 300px;
}

这当然适用于所有图像,因此您可能需要为 img-bar 中的图像添加一个类,或者为包含主图像的 figure 元素设置尺寸。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2019-10-15
    • 2015-10-29
    相关资源
    最近更新 更多