【发布时间】:2020-11-01 21:47:43
【问题描述】:
我正在尝试将 4 个图像放在父 flexbox 中的 flexbox div 中,总高度为 100%,而不会超出父 flexbox。我搜索了很多,但没有找到有用的东西。
我做了一个最小的例子:
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
display: flex;
}
main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
background-color: yellowgreen;
}
.imgs {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
.img100 {
max-width: 100%;
max-height: 100%;
vertical-align: middle;
}
<main>
<!--
Weird. Chromium (Chrome & new Edge) usually renders height 100%,
but not height-responsive; sometimes renders scroll bar.
Firefox always renders the scroll bar result.
-->
<div class="imgs">
<img class="img100" src="https://imgur.com/ruE1EBV.jpg">
</div>
<div class="imgs">
<img class="img100" src="https://imgur.com/ruE1EBV.jpg">
</div>
<div class="imgs">
<img class="img100" src="https://imgur.com/ruE1EBV.jpg">
</div>
<div class="imgs">
<img class="img100" src="https://imgur.com/ruE1EBV.jpg">
</div>
</main>
当打开这个例子时,基于 chromium 的浏览器(Chrome,new Edge)通常会呈现 100% 的高度,这是期望的结果,但它不是“高度响应的”:一旦页面被加载,图像的最大高度保持不变完全读取。 更糟糕的是,有时他们会用滚动条给出拉伸的结果;并且 Firefox 总是给我带有滚动条的拉伸结果,这不是我想要的。
尝试打开此 S.O. Chromium 和 Firefox 中的页面,然后运行 sn-p.结果也不同。
有什么方法可以实现我想要的吗?包装 div 和父 div 可能不是 flexbox。我只希望图像保留在 div 中,具有宽度响应和高度响应。
另外,Chromium 浏览器的渲染结果不一致的原因是什么?我的示例是否遗漏了什么?
我知道我可以使用背景图像技术,所以我可以将图像放在 div 中而根本不改变布局。但是我只想要图片部分可点击,所以那里一定有对应可点击区域的图片元素。
背景图片示例:
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
display: flex;
}
main {
flex: 1;
display: flex;
flex-direction: column;
background-color: yellowgreen;
}
a {
flex: 1;
background-image: url('https://imgur.com/ruE1EBV.jpg');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
border: 5px solid red;
}
<main>
<a href="https://stackoverflow.com"></a>
<a href="https://stackoverflow.com"></a>
<a href="https://stackoverflow.com"></a>
<a href="https://stackoverflow.com"></a>
</main>
编辑:
当里面的内容不包含任何图像时,flex-direction: column 中的行高相等是可以的。我认为棘手的部分是图像。他们只是伸展......
html {
height: 100%;
}
body {
height: 100%;
margin: 0;
display: flex;
}
main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
background-color: yellowgreen;
}
.imgs {
flex: 1;
display: flex;
justify-content: center;
align-items: center;
border: 5px solid red;
}
.img100 {
max-width: 100%;
max-height: 100%;
vertical-align: middle;
}
<main>
<div class="imgs">
hello
</div>
<div class="imgs">
hello
</div>
<div class="imgs">
hello
</div>
<div class="imgs">
hello
</div>
</main>
【问题讨论】:
-
这可能与:stackoverflow.com/questions/47320518/… 有关,但这只是猜测。 flex-direction 中的行高似乎相等:官方不支持列。但如果是这样的话,它并不能解释为什么它可以在 Chrome 中运行。
-
与网格布局等效的是将
上的 display: flex; flex-direction: column;替换为display: grid; grid-auto-rows: 1fr; -
我只是添加了一个使用 flexbox 的相同行高的示例。但是如果里面有图像,也许就不可能了。我会尝试网格布局。谢谢。
-
我看到你的编辑是用文字而不是图片。它似乎可以工作,但如果文本足够长(跨越几行),它将无法正常工作,例如如果一行有 3 行文本,另一行有 2 行,则后一行不会拉伸以匹配较长的行。 ;)
-
看来flexbox并没有缩小其内容以保持布局?它只是成长......