简体   繁体   中英

Stack CSS Grid element without media queries

I'm looking to stack 2 columns once they get too "squished" in the viewport using CSS grid.

Right now I have:

<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>

The columns just seem to grow to 100% in width rather than stacking. Is there a way to do this without the media query?

Use flex property instead of grid

.grid{
  display: flex;
  justify-content:space-between;
  flex-wrap:wrap;
}

Seems that you are looking for an automatic number of columns.

The syntax repeat in grid-template-columns allows for the keyword auto-fit . When using this keyword, the column count will be adjusted so that the max column width will not overflow the grid width.

In the snippet, setting a max width of 300px makes the grid have only 1 column when it's size is 550px:

 .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> 

Yes we can achieve it using flex box

Here is the sample piece of code where we can wrap our elements to new line when it reaches certain width without writing any external media queries.

Only we need to do is like apply the below properties in the parent element

display: flex; flex-wrap: wrap; justify-content: start;

Even this is one of the advantage of using flex-box concept.

 .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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM