I want grid container to maintain square shape. So when screen is resized, it will get bigger or smaller, but it's height will be always same as it's width. I want to place 3 images inside, with top one taking up two columns, and bottom ones are square taking one column each.
HTML:
<div class='container'>
<div class='grid'>
<img></img>
<img></img>
<img></img>
</div>
</div>
SASS:
.container: {
background: #fff;
max-width: 600px;
padding: 10px;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: 10px;
& > img:first-child {
grid-column: 1 / span 2;
grid-row: 1;
}
img {
width: 100%;
background-color: #000;
object-fit: cover;
}
}
我尝试向网格添加伪元素以保持平方比,却发现它不适用于网格。我尝试给予img
height: 100%
但它弄得太长了。
我发现了一些关于如何使图像保持方形的问题,但没有一个是关于如何保持网格容器方形并防止被儿童拉伸的。
我会做以下事情:
- 使网格宽度和高度响应式调整大小 - 用于此用途这个方法 https://spin.atomicobject.com/2015/07/14/css-responsive-square/ (
.container
and &::after
伪元素)
- 使网格本身遵循容器的正方形宽度和高度(
.grid-wrapper
)
- 使用图像容器,以便容器在网格内调整大小(第一行 = 2 列宽,第二行 = 2x1 列)(
.grid-box
)
- 在 div 中使用绝对定位图像,因此它们实际上覆盖了 div
HTML 代码:
<div class='container'>
<div class='grid-wrapper'>
<div class='grid'>
<div class="grid-box">
<img src="https://picsum.photos/200/300"></img>
</div>
<div class="grid-box">
<img src="https://picsum.photos/200/300"></img>
</div>
<div class="grid-box">
<img src="https://picsum.photos/200/300"></img>
</div>
</div>
</div>
</div>
SAS 代码:
$-gutter: 10px;
$-max-width: 600px;
* {
box-sizing: border-box;
}
.container {
position: relative;
max-width: $-max-width;
width: 100%;
background: #ffff00;
&::after {
content: "";
display: block;
padding-bottom: 100%;
}
}
.grid-wrapper {
position: absolute;
width: 100%;
height: 100%;
padding: $-gutter;
}
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
gap: $-gutter;
width: 100%;
height: 100%;
&-box {
position: relative;
width: 100%;
height: 100%;
&:first-child {
grid-column: 1 / span 2;
}
}
img {
position: absolute;
width: 100%;
height: 100%;
background-color: #000000;
object-fit: cover;
}
}
这是一个小提琴演示:https://jsfiddle.net/robertp/uLfj1swm/ https://jsfiddle.net/robertp/uLfj1swm/
And a screenshot of how this solution renders:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)