img 不考虑 html 中的宽度(使用 flexbox) [英] Img doesn't respect width in html (with flexbox)

查看:43
本文介绍了img 不考虑 html 中的宽度(使用 flexbox)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<html lang="en"><头><title>您的页面标题在这里</title><meta charset="utf-8";/><元名称=视口"内容=宽度=设备宽度,初始比例=1";/><link rel="样式表";href="index.css";/><身体><div class="container"><h1>我的相册</h1><div class="gallery"><图><img src="img/dog1.jpeg";alt=第一只狗"><figcaption>示例照片</figcaption></图><div class="img-bar"><img src=img/dog2.jpeg";alt=第二只狗"/><img src="img/dog3.jpeg";alt=第三只狗"/><img src="img/dog4.jpeg";alt=第四只狗"/><img src="img/dog5.jpeg";alt=第五只狗"/>

</html>

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

.img-bar{显示:弹性;}图像{宽度:100%;}.img-bar img {适合对象:覆盖;宽度:300px;高度:300px;}

所有的图像文件都有尺寸>300 像素 x 300 像素,所以我希望它们遵循 CSS 规则.但是,正如您从下面的照片中看到的,第二张图片不符合规则(高比宽).仅供参考,该图像文件的实际尺寸为 934 像素 x 1401 像素.

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

解决方案

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

img {宽度:100%;高度:100%;适合对象:封面;}.img-bar {显示:弹性;宽度:300px;高度:300px;}

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

I have some html that should create an image up top, and an image gallery underneath.

<!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>

In order to style the image gallery, I've added the following styles:

.img-bar{
  display: flex;
}

img {
  width: 100%;
}

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

All of the image files have dimensions > 300px by 300px, so I would expect them to follow the CSS rules. However, as you can see from the photo below, the second image doesn't follow the rules (it's taller than it is wide). As an fyi, the actual dimensions of that image file are 934px x 1401px.

Any help would be appreciated! Thanks.

解决方案

You want to set the dimensions of your container, then have the image inside expand to fill it. I'd reshuffle it like this:

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

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

This will of course apply to all images, so you might want to either add a class for the images inside img-bar or set the dimensions for your figure element containing the main image.

这篇关于img 不考虑 html 中的宽度(使用 flexbox)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆