当遍历项目以在每个奇数或偶数项目之前和之后添加div时,我可以这样做,但是我想知道是否有一种方法可以通过JUST CSS flex来完成。
我想摆脱.col div而只使用CSS。
我需要显示一行水平滚动的项目或显示两行水平滚动的项目。
第一行用于移动设备屏幕,第二行用于任何大于移动设备的屏幕。
这是一支笔
https://codepen.io/modemlooper/pen/rXWaVK
const items = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let html = "";
const device = "tablet";
items.map((item, index) => {
html +=
"tablet" === device && index % 2 === 0 ? '<div class="col">' : "";
html += '<div class="slide"><div>' + item + "</div></div>";
html += "tablet" === device && index % 2 !== 0 ? "</div>" : "";
});
var e = document.createElement("div");
e.className += " box";
e.innerHTML = html;
document.querySelector(".wrap").appendChild(e);
.wrap {
display: flex;
height: 100%;
align-items: center;
}
.box {
display: flex;
background-color: #2c3e50;
min-width: 100%;
overflow-x: auto;
box-sizing: border-box;
}
.box::-webkit-scrollbar {
display: none;
}
.slide {
box-sizing: border-box;
padding: 20px;
}
.slide>div {
min-width: 218px;
height: 178px;
display: flex;
box-sizing: border-box;
}
.slide:nth-child(odd)>div {
background: red;
}
.slide:nth-child(even)>div {
background: blue;
}
.col:nth-child(odd) .slide:nth-child(odd)>div {
background: red;
}
.col:nth-child(even) .slide:nth-child(even)>div {
background: red;
}
.col:nth-child(even) .slide:nth-child(odd)>div {
background: blue;
}
.col:nth-child(odd) .slide:nth-child(even)>div {
background: blue;
}
<div class="wrap"></div>
答案 0 :(得分:0)
应符合您的需求。仅使用CSS
。
.wrap {
display: flex;
}
.box {
box-sizing: border-box;
width: 220px;
height: 160px;
margin: 20px;
background-color: #2c3e50;
flex-shrink: 0;
}
/* DESKTOP */
@media (min-width: 1024px) {
.wrap {
flex-direction: column;
flex-wrap: wrap;
align-content: flex-start;
height: 400px;
}
}
<div class="wrap">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>