繁体   English   中英

弹性项目宽度总是等于图像内容的内在宽度

[英]flex item width is always equal to intrinsic width of image content

目标

  1. 我想在 div(child) 中设置一个图像,它是 flex 容器 div(parent) 中的一个 flex 项。
  2. 我希望图像的高度等于其包含的 div(child),同时仍保持其纵横比。

我的理解

  1. 如果我将图像的高度设置为 100%,那么图像将更改其大小以匹配包含的 div(child) 高度,同时仍保持其纵横比。 (这按预期工作)
  2. 在缩放以匹配其容器高度后,包含 div(child) 的宽度将等于图像的新宽度。 (这不能按预期工作)

问题

容器 div(child) 的宽度等于图像的固有宽度,而不是按比例缩小图像的新宽度,在容器 div(child) 的右侧留下额外的空间。

<html>
   <head>
      <style>
         .parent {
             display: flex;
             width: 1000px;
             height: 400px;
             padding: 10px 0px;
             background-color: red;
         }
         .child {
             padding: 10px 0px;
             background-color: blue;
         }
         .child > img {
             height: 100%;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div class="child">
            <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
         </div>
      </div>
   </body>
</html>

 .parent { display: flex; width: 1000px; height: 400px; padding: 10px 0px; background-color: red; }.child { padding: 10px 0px; background-color: blue; }.child > img { height: 100%; width: 100%; object-fit: cover; }
 <html> <body> <div class="parent"> <div class="child"> <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img"> </div> </div> </body> </html>

您可以将图像的宽度设置为 100%,这样它将占用整个 div。 为了使图像不丢失像素,您可以添加object-fit:cover; 这是工作示例https://codepen.io/maha986/pen/BaWqrGb

如果你想减小子 div 的大小,那么你可以将它的宽度设置为你想要的任何值

你可以让你的孩子和图像造型像这样

         .child {

             padding: 10px 0px;
           width:500px;

             background-color: blue;

         }

         .child > img {

             height: 100%;
width:100%;

         }

我不确定这是否是正确的方法,但我最终通过添加height: 100%;解决了这个问题。 .child以及到.child > img 这是最终代码:

<html>
   <head>
      <style>
         .parent {
             display: flex;
             width: 1000px;
             height: 400px;
             padding: 10px 0px;
             background-color: red;
         }
         .child {
             height: 100%;
             background-color: blue;
         }
         .child > img {
             height: 100%;
         }
      </style>
   </head>
   <body>
      <div class="parent">
         <div class="child">
            <img src="https://cdn.pixabay.com/photo/2015/04/19/08/32/marguerite-729510_960_720.jpg" alt="some img">
         </div>
      </div>
   </body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM