我有一个可以包含 2、3 或 4 个元素的包装器(我事先不知道,因为每个元素都会呈现自身,具体取决于 API 响应)。
如果有 3 个(或更少),我希望它们像这样堆叠:
没什么大不了的。但是当有 4 个时,我需要这个其他布局:
到目前为止,我认为 CSS Grid 是可行的方法并且我尝试了:
/* Just to add some interaction to the demo */
const w = document.getElementById("wrapper");
let x;
function toggle(event) {
const d = document.getElementById("D");
return d
?
x = d.cloneNode() && w.removeChild(d)
: w.appendChild(x);
}
#wrapper {
width: 100%;
max-width: 500px;
display: grid;
grid-template-columns: 1fr 1fr;
grid-gap: 10px;
}
.item {
grid-column-start: span 2
}
.item:nth-last-child(1),
.item:nth-last-child(2) {
grid-column-start: auto;
}
/* Non-relevant CSS here: */
button {
margin: 20px auto;
font-size: 16px;
padding: 3px 6px;
border-radius: 6px;
}
#A { background: #7984f7 }
#B { background: #cb8af8 }
#C { background: #8cd4fb }
#D { background: #97f8d8 }
.item {
border-radius: 6px;
padding: 10px 0;
font-family: sans-serif;
font-weight: bold;
color: white;
text-align: center;
}
<div id="wrapper">
<div id="A" class="item">A</div>
<div id="B" class="item">B</div>
<div id="C" class="item">C</div>
<div id="D" class="item">D</div>
</div>
<button onclick="toggle()">Click me!</button>
但它不适用于 3 个元素......事实上,我已经尝试了很多东西(所有 CSS Grid 相关)并且可能有一个更简单的解决方案我现在看不到......任何帮助都会非常感谢!
最佳答案
我建议使用 flexbox。对于给定的三种可能性,请在下面的代码片段中使用这个简单的 CSS。
基本上,您可以让元素排成一行,但如果它们不合适则进行换行。您使前两个元素占据所有宽度,以便每行只有一个。对于第 3 和第 4 个,你将它们的 flex-basis(初始宽度)设置为更小的值,并在有空间时使它们增长(flex-grow:1)。
.examples{
display: flex;
flex-direction: row;
align-items: flex-start;
}
.container{
width: 200px;
border: 1px solid red;
display: flex;
flex-direction: row;
flex-wrap: wrap;
align-items: flex-start;
}
.box{
height: 50px;
background-color: blue;
margin: 5px;
border-radius: 5px;
flex-basis: 200px;
}
.box:nth-child(3), .box:nth-child(4){
flex-basis: 50px;
flex-grow: 1;
}
<div class="examples">
<div class="container">
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
解决方案也在这里:JSFiddle
关于html - 布局取决于元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54794007/