我是 flexbox 的新手,并尝试使用它来布置最多 6 张照片的照片拼贴,如下所示:
我希望照片按编号排列,这样当少于 6 张照片时,上面每张照片的位置保持不变,只为缺少的照片留出空白。
这是我得到的:
<html>
<head>
<style type="text/css">
.container {
width: 600px;
height: 600px;
background-color: blue;
display: flex;
flex-direction: column;
flex-wrap: wrap;
}
.photo {
background-color: red;
}
.large {
width: 400px;
height: 400px;
}
.small {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div class="container">
<div class="photo large">Photo 1</div>
<div class="photo small">Photo 2</div>
<div class="photo small">Photo 3</div>
<div class="photo small">Photo 4</div>
<div class="photo small">Photo 5</div>
<div class="photo small">Photo 6</div>
</div>
</body>
</html>
但这是在产生这种布局:
出于某种原因,flex-wrap 没有将照片 3 放在我想要的位置,即使它有空间。我试过摆弄 justify-content 和 align-items,但似乎无法正常工作。
有没有办法在不引入更多
最佳答案
CSS 网格解决方案
由于您对 CSS Grid 没有任何限制,所以看看在 x 和 y 方向上布置元素时它能为您做什么。 grid-template-area
属性使处理这种类型的布局变得微不足道。您在父元素中定义模板区域,然后将子元素放置在您想要的任何区域中。你可以想象这真的打开了你在不同的响应/自适应环境中可以做的事情。
.container {
width: 600px;
height: 600px;
background-color: blue;
display: grid;
grid-template-areas: "largetop largetop smalltop1"
"largetop largetop smalltop2"
"smallbottom1 smallbottom2 smallbottom3";
}
.photo-1 {
grid-area: largetop;
}
.photo-2 {
grid-area: smallbottom1;
}
.photo-3 {
grid-area: smallbottom2;
}
.photo-4 {
grid-area: smalltop1;
}
.photo-5 {
grid-area: smalltop2;
}
.photo-6 {
grid-area: smallbottom3;
}
.photo {
background-color: red;
}
.large {
width: 400px;
height: 400px;
}
.small {
width: 200px;
height: 200px;
}
<div class="container">
<div class="photo photo-1 large">Photo 1</div>
<div class="photo photo-2 small">Photo 2</div>
<div class="photo photo-3 small">Photo 3</div>
<div class="photo photo-4 small">Photo 4</div>
<div class="photo photo-5 small">Photo 5</div>
<div class="photo photo-6 small">Photo 6</div>
</div>
Flexbox 解决方案
一旦大照片占用了可用的容器空间,以下两项将通过 flex-wrap: wrap
换行到下一行。
.container {
width: 600px;
height: 600px;
background-color: blue;
display: flex;
/* row direction */
}
.left {
display: flex;
flex-wrap: wrap;
flex-basis: 400px;
}
.photo {
background-color: red;
}
.large {
width: 400px;
height: 400px;
}
.small {
width: 200px;
height: 200px;
}
<div class="container">
<div class="left">
<div class="photo large">Photo 1</div>
<div class="photo small">Photo 2</div>
<div class="photo small">Photo 3</div>
</div>
<div class="right">
<div class="photo small">Photo 4</div>
<div class="photo small">Photo 5</div>
<div class="photo small">Photo 6</div>
</div>
</div>
关于html - 使用 flexbox 最多 6 张照片的照片拼贴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55093761/