现在我正在使用 flexbox 创建一个包含三列的图像库。 (我不确定这是否通过 flexbox 或网格更好地实现,但 flexbox 对我来说很有意义,因为我不想要固定的网格)。
但是,我似乎无法想出一种方法来使项目在交叉轴上相互粘附。例如,这是我的画廊的样子 当我想要的行为是 ,其中图像 E 和 F 分别贴在 B 和 C 上。
flexbox如何实现?或者,如果不能,是否可以使用网格?
这不是用 grid 和 flex 都无法实现的(grid masonry 做到了,但还没有实现)。您必须使用具有 3 列的网格,并且每列都是一个 flex 容器。 (这可以做不同的)
body {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 2rem;
}
body>div {
display: flex;
flex-direction: column;
gap: 2rem;
}
body>div:nth-child(1) div:first-child {
block-size: 100px;
background-color: coral;
}
body>div:nth-child(1) div:last-child {
block-size: 120px;
background-color: blueviolet;
}
body>div:nth-child(2) div:first-child {
block-size: 90px;
background-color: aquamarine;
}
body>div:nth-child(2) div:last-child {
block-size: 80px;
background-color: brown;
}
body>div:nth-child(3) div:first-child {
block-size: 130px;
background-color: bisque;
}
body>div:nth-child(3) div:last-child {
block-size: 50px;
background-color: violet;
}
<body>
<div>
<div>A</div>
<div>B</div>
</div>
<div>
<div>C</div>
<div>D</div>
</div>
<div>
<div>E</div>
<div>F</div>
</div>
</body>
可以单独使用 flexbox 来完成,但它比它的价值更麻烦,你需要重新排列 img 顺序,下面的代码片段。 Css 代码可以更短,这只是为了向您展示它是可以做到的。您还可以自定义百分比/边距/任何适合您项目需求的内容。它还具有您可以向列中添加其他块的优点;它是响应式的+我添加了填充/边框所以你可以更好地理解它是如何工作的。
.main-container {
border:1px solid red;
width 100%;
display:flex;
padding: 10px;
gap: 10px;
}
.row{
width: 33%;
height: 300px;
padding: 10px;
display: flex;
flex-direction: column;
}
.left,
.middle,
.right{
border: 1px solid black;
gap: 10px;
}
.left div,
.middle div,
.right div {
width: 100%;
color:white;
text-align: center;
padding-top: 10px;
font-size: 26px;
font-weight: 600;
}
.left div:first-child {
background-color: red;
height: 40%;
}
.left div:last-child {
background-color: blue;
height: 60%;
}
.middle div:first-child {
background-color: green;
height: 20%;
}
.middle div:last-child {
background-color: orange;
height: 80%;
}
.right div:first-child {
background-color: purple;
height: 73%;
}
.right div:last-child {
background-color: brown;
height: 27%;
}
<div class="main-container">
<div class="left row">
<div>A</div>
<div>B</div>
</div>
<div class="middle row">
<div>C</div>
<div>D</div>
</div>
<div class="right row">
<div>E</div>
<div>F</div>
</div>
</div>