如何根据页面宽度将动态网格设置为两列或一列?



我的项目必须对齐两列或一列(媒体断点定义 - 移动应该是单列(。

项目的顺序在两列或一列之间不同。

项目数是动态的。

项目的大小(高度(是动态的。

两列中的示例可能需要:

left.one right.one
left.two right.two
left.three

因为高度是动态的,所以左边的顶部。二 可能高于右边的顶部。二...

在一列中,它可能会对齐:

left.one 
left.two 
right.one
right.two
left.three

我可以在呈现项目时动态地将单列(或两列(类分配给项目。

如何在两列视图中时,如何为此内容设置网格,而无需有条件地包装列内容(即,没有外部div.left 和div.right,只有在内容为两列时才能附加到 DOM(?这种方法的问题在于它依赖于JavaScript(我已经有了这个解决方案(。如果可能的话,我想纯粹在 CSS 中解决这个问题。

我不打算发布我的工作解决方案,因为就像我说的,在渲染两列时,它依赖于 JavaScript 将每列内容包装在外部div 中。

注意:这不是答案。 这只是比原始演示稍微更好地说明了问题

:root {
--gridColumns: 2;
}
.left,
.right {
padding: 10px;
margin: 10px;
color: white;
background-color: grey;
border-radius: 2px;
}
.grid {
display: grid;
background-color: lightgrey;
grid-template-columns: repeat(var(--gridColumns), 1fr);
}
@media screen and (max-width: 400px) {
:root {
--gridColumns: 1;
}
}
<div class="grid">
<div class="left one">left one</div>
<div class="right one">right one</div>
<div class="left two">left two</div>
<div class="right two">right two</div>
<div class="left three">left three</div>
</div>

一种方法如下,这确实需要更改最初发布的网格项的顺序。

:root {
/* using CSS Custom properties ('CSS Variables') to
simplify some aspects of the presentation update: */
--gridColumns: 2;
}
.left,
.right {
padding: 10px;
margin: 10px;
color: white;
background-color: grey;
border-radius: 2px;
}
.grid {
display: grid;
background-color: lightgrey;
/* here we use the custom property defined earlier, introducing that
property-value to the repeat() function via the var() function;
the repeat() function defines the number of tracks along with the
size of those tracks: */
grid-template-columns: repeat(var(--gridColumns), 1fr);
}
/* using CSS media queries to update the custom property for
display on devices using a screen with widths smaller than
400px: */
@media screen and (max-width: 400px) {
:root {
--gridColumns: 1;
}
}
/* for those devices with a screen greater than 400px in width: */
@media screen and (min-width: 400px) {
.grid {
/* we set the grid-auto-flow property to 'dense' in order
to avoid empty cells: */
grid-auto-flow: dense;
}
.left {
/* placing all grid-items with the 'left' class-name into
the first grid-column: */
grid-column: 1;
}
.right {
/* placing all grid-items with the 'right' class-name into
the second grid-column: */
grid-column: 2;
}
}
<div class="grid">
<div class="left one">left one</div>
<div class="left two">left two</div>
<div class="right one">right one</div>
<div class="right two">right two</div>
<div class="left three">left three</div>
</div>

JS小提琴演示。

引用:

  • CSS 自定义属性。
  • grid-auto-flow.
  • repeat().
  • var().

最新更新