【发布时间】:2019-07-14 14:17:24
【问题描述】:
我有一个可以包含 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 网格相关)并且可能有一个更简单的解决方案我现在看不到...任何帮助都会非常感谢!
【问题讨论】:
标签: html css flexbox alignment css-grid