我可以添加一个边界之间的伸缩iItems在同一行?



我想在同一行的伸缩项之间添加边框。我有flex-wrap: wrap;集,所以我需要一种方法来检测flex项目是否与另一个flex项目在一行中,或者当页面呈现时它是否在自己的行中(它可能是)。

如果它与另一个伸缩项占用一行,则在这种情况下我将添加分隔符,否则,不添加分隔符。我怎么才能做到呢?

从这个答案

在CSS中,一旦浏览器在初始级联上呈现页面,它就不会在元素换行时重新流进文档。因此,父元素不知道它们的子元素何时换行。

这就是为什么容器在包装后不会收缩以适应其内容。

这就是为什么你需要媒体查询或JavaScript。

知道了这些,这里有一个使用JavaScript在必要时插入分隔符的例子。

var items = document.querySelectorAll(".item");
var firstItemInCurrentRow = items[0];
items.forEach(item => {
// Check if the current item is at the same
// height as the first item in the current row.
if (item.offsetTop === firstItemInCurrentRow.offsetTop) {
// Don't apply the style to the first item
// in the current row.
if (item !== firstItemInCurrentRow) {
// Add the divider.
item.style.borderLeft = "1px solid black";
item.style.paddingLeft = "5px";
}
}
else {
// This item was lower, it must be
// the first in a new row.
firstItemInCurrentRow = item;
}
});
.container {
display: flex;
flex-direction: row;
flex-wrap: wrap;
background-color: lightgray;
width: 100%;
}
.item {
flex-basis: 200px;
background-color: darkgray;
}
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
</div>

没有直接的方法。您有两个选项:

  1. 如果您可以期望在不同的屏幕尺寸下每行中的项目计数,您可以使用@media查询并根据屏幕尺寸设置边框,例如:如果预计将有5(min-width: 1024px)上除最后一行外的每一行项,然后你可以输入:

    .item {
    border-right: 1px solid red;
    }
    @media only screen and (max-width: 1024px) {
    .item:nth-child(5n), .item:last-child {
    border-right: none;
    }
    }
    
  2. 如果您的行将更加动态并且没有预期的计数,则需要使用JavaScript。例如,循环条目并检查它们的offsetTop,对于具有相同值的每个条目,除了第一个,添加左边框,然后对下一个值执行相同的操作(这意味着您在不同的行上),等等!

唯一的单条目将是最后一个。

所以你可以为所有这些项目使用边框,并在第一个和最后一个上删除它。

#container {
display: flex;
flex-wrap: wrap;
width: 220px;
}
.flex-item {
width: 100px;
height: 100px;
background: aliceblue;
border-left: 5px solid black;
}
.flex-item:first-child, .flex-item:last-child {
border-left: none;
}
<div id="container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>

最新更新