繁体   English   中英

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

[英]img set flex-grow to fill flex container rest space, it cause flex inner overflow flex container

以下是我的代码,“text1”溢出了弹性容器,我希望弹性容器中的 img + 文本和 img 填充弹性容器休息

<!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 剩余空间,我很困惑为什么 img 会导致内部溢出

以下是我的“img.jpg”

在此处输入图片说明

添加此代码以对您的代码进行映像

.c img{
   flex-grow: 1;
   object-fit: contain;
   flex-basis:100%;
   width:100%;
}

 /* 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>

抱歉,我误解了你的问题。

有更简单的方法可以做到这一点。 你可以用background-image做到这一点:

 <!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; background-image: url('https://i.stack.imgur.com/P5N3A.jpg'); background-repeat: no-repeat; background-size: contain; } </style> </head> <body> <div class="c"> <div>text1</div> </div> </body> </html>

或者你可以用<figure> & <figcaption>

 <!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; width: 100px; height: 100px; position: relative; } figcaption { color: white; position: absolute; bottom: 0; left: 0; } </style> </head> <body> <figure class="c"> <img src="https://i.stack.imgur.com/P5N3A.jpg"> <figcaption>text1</figcaption> </figure> </body> </html>

希望这可以帮助!

暂无
暂无

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

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