column-fill: auto;使用后column-count: 2;无效
时间: 2024-02-10 15:10:57 浏览: 156
非常抱歉,我的回答有误。在使用`column-fill: auto`时,`column-count`属性确实会失效,因为`column-fill`属性会根据元素的高度自动填充每一列,而不是像`column-count`属性一样强制指定列数。
如果您想要保持原来的渲染顺序不变,并且同时使用瀑布流布局,您可以考虑使用JavaScript来实现。具体来说,您可以先将元素按照原来的顺序排列好,然后再使用JavaScript将它们逐个添加到瀑布流布局中。
以下是一个示例实现:
```html
<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 class="item">Item 6</div>
<div class="item">Item 7</div>
<div class="item">Item 8</div>
<div class="item">Item 9</div>
<div class="item">Item 10</div>
</div>
```
```css
.container {
column-count: 2;
}
.item {
break-inside: avoid-column;
}
```
```javascript
const container = document.querySelector('.container');
const items = Array.from(document.querySelectorAll('.item'));
let columnHeights = [0, 0];
items.forEach((item, index) => {
const minHeight = Math.min(...columnHeights);
const columnIndex = columnHeights.indexOf(minHeight);
item.style.gridColumn = columnIndex + 1;
item.style.gridRow = `span ${Math.ceil(item.offsetHeight / minHeight)}`;
columnHeights[columnIndex] += item.offsetHeight;
container.appendChild(item);
});
```
在上面的示例中,我们首先使用CSS设置容器元素为两列布局,然后使用`break-inside: avoid-column`属性来防止元素被分割到不同的列中。
接着,我们使用JavaScript来实现瀑布流布局。具体来说,我们首先将所有的元素按照原来的顺序排列好,然后使用`Math.min()`方法找到当前两列中高度较小的那一列,然后将元素添加到该列中。为了防止元素被分割到不同的列中,我们使用`grid-column`属性将元素放置到正确的列中,使用`grid-row`属性设置元素的行数,以及使用`columnHeights`数组来记录每一列的高度。
希望这个示例能够帮助您解决问题。如果您还有其他问题,请随时提出。
阅读全文
相关推荐

















