我一直在寻找解决这个问题的方法将近两个星期,但我仍然完全迷失了方向。我正在制作一个简单的登陆页面,我不想要任何滚动。我需要一个标题,后跟一个包含段落和图像的 Bootstrap 行。这是我的 ms 油漆示例:
够简单吧?好吧,我一生都无法弄清楚如何使该图像缩小以适应该行。这就是我现在发生的事情。注意:当您在 stackoverflow 上运行代码段时,窗口很小。使用 JSFiddle 更容易查看发生了什么
body, html {
height: 100%;
width: 100%;
position: absolute;
margin: 0;
}
.content {
}
img {
height: 100%;
}
h1 {
background-color: white;
}
.banner {
height: 90%;
background-color: red;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<div class="banner">
<h1>
Header
</h1>
<div class="row content">
<p> Hello World </p>
<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png">
</div>
</div>
结果
让我失望的部分是
.row
超出其父容器 .banner
.我们如何强制它留在那个红色区域内?我已经搞砸了 object-fit、flex-grow、flex-shrink、flex-basis 并且这些似乎都没有创建所需的行为。我要疯了,试图解决这个问题。也许 flexbox 是在这里使用的错误工具?但我正在尝试利用 Bootstrap 网格系统的媒体查询。提前感谢您的帮助!
注意:我将所有内容都嵌套在
<div class=".banner">
中的原因是因为我希望标题在红色背景上有阴影。编辑
我的问题的根源是如何让图像适合仅覆盖红色区域的行内?
最佳答案
您可以更新您的代码,如下所示:
img {
/* this will make the image stretch and no overflow*/
height:0;
min-height:100%;
/**/
}
h1 {
background-color: white;
}
.banner {
height: 90vh;
background-color: red;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" >
<div class="banner d-flex flex-column"> <!-- flex container here -->
<h1>
Header
</h1>
<div class="d-flex content flex-grow-1 p-2"> <!-- flex-grow here to fill remaining space -->
<p> Hello World </p>
<img src="https://upload.wikimedia.org/wikipedia/commons/8/89/Portrait_Placeholder.png" class="ml-auto">
</div>
</div>
关于css - 如何强制图像缩小以适应 flexbox?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62506922/