img 设置 flex-grow 填充 flex 容器剩余空间,导致 flex 内部溢出 flex 容器

2022-01-19 00:00:00 frontend javascript html css flexbox

以下是我的代码,text1";溢出 flex 容器,我希望 flex 容器中的 img + text 和 img 填充 flex 容器休息

following is my code, "text1" overflow the flex container, I expect img + text in flex container and img fill flex container rest

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!--mobile friendly-->
    <meta name="viewport" content="width=device-width, user-scalable=yes">
    <style>
        .c {
            display: flex;
            flex-direction: column;
            width: 100px;
            height: 100px;
            border: 5px solid lightblue;
        }

        .c img {
            flex-grow: 1;
            object-fit: contain;
        }
    </style>
</head>
<body>
<div class="c">
    <img src="./img.jpg"/>
    <div>text1</div>
</div>
</body>
</html>

结果是:

如果元素不是 img 并且是 div,flex-grow: 1 将填充 flex rest 空间,我很困惑为什么 img 会导致内部溢出

if element is not img and is div, flex-grow: 1 will fill flex rest space, I'm confused why img cause inner overflow

以下是我的img.jpg"

following is my "img.jpg"

推荐答案

/* CSS */

.c {
  width: 100px;
  height: 100px;
  border: 5px solid lightblue;
  position: relative;
  text-align: center;
}
.c img {
  width: 100%;
}
.c div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: red;
}

<!-- HTML -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=yes">
  </head>
  <body>
    <div class="c">
      <img src="https://i.stack.imgur.com/P5N3A.jpg" />
      <div>text1</div>
    </div>
  </body>
</html>

相关文章