[英]Stack CSS Grid element without media queries
我希望使用CSS网格在视口中过于“压缩”时堆叠2列。
现在我有:
<style>
.grid{
display: grid;
grid-template-columns: 1fr 260px;
grid-gap: 1em;
}
@media only screen and (min-width:600px) {
.grid {
grid-template-columns: 100% 100%;
}
}
</style>
<div class="grid">
<main>More stuff here...</main>
<aside>Stuff inside here...</aside>
</div>
列的宽度似乎只是增加到100%,而不是堆积。 没有媒体查询,有没有办法做到这一点?
使用flex属性而不是grid
.grid{
display: flex;
justify-content:space-between;
flex-wrap:wrap;
}
似乎您正在寻找自动列数。
grid-template-columns中的语法重复允许关键字auto-fit 。 使用此关键字时,将调整列数,以使最大列宽不会超出网格宽度。
在代码段中,将最大宽度设置为300px会使网格在大小为550px时只有1列:
.grid{ display: grid; grid-template-columns: repeat(auto-fit, minmax(auto, 300px)); grid-gap: 1em; border: solid 1px black; margin: 10px; } #grid1 { width: 550px; } #grid1 { width: 650px; } main { background-color: yellow; } aside { background-color: lightblue; }
<div class="grid" id="grid1"> <main>More stuff here...</main> <aside>Stuff inside here...</aside> </div> <div class="grid" id="grid2"> <main>More stuff here...</main> <aside>Stuff inside here...</aside> </div>
是的,我们可以使用flex box
实现它
这是示例代码,当元素达到一定宽度时,我们可以将元素包装到新行中,而无需编写任何外部媒体查询。
只有我们需要做的就像在父元素中应用以下属性
display: flex; flex-wrap: wrap; justify-content: start;
甚至这也是使用flex-box概念的优势之一。
.container { display: flex; flex-wrap: wrap; justify-content: start; } .column-1, .column-2, .column-3 { width: 250px; height: 100px; margin: 5px; } .column-1 { background: green; } .column-2 { background: red; } .column-3 { background: yellow; }
<div class="container"> <div class="column-1"></div> <div class="column-2"></div> <div class="column-3"></div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.