问题
I'm trying to create a four column layout where each column grows and shrinks with the size of the window, but each column has a minimum width and when the window is too small for all four columns to fit in a single row, it transitions to a single column with each section taking up the full width.
I've been unable to do this with either flex-box or CSS grid. And I'd like to do this without a media query. Using a media query would solve the issue pretty easily, but I don't like them!
.col {
width: 100%;
display: flex;
flex-wrap: wrap;
}
.section {
margin: 10px 0px 0px 10px;
min-width: 250px;
height: 400px;
background-color: gray;
flex: auto;
}
<div class="col">
<div class="section">
</div>
<div class="section">
</div>
<div class="section">
</div>
<div class="section">
</div>
</div>
And a codepen: https://codepen.io/WriterState/pen/oRKxMj
回答1:
Media queries are great, but they are not always a viable substitute for container queries (which sadly do not exist).
A horizontal to vertical layout switch can be achieved using CSS calc
when you know how many columns you will have.
.child{
min-width: 25%; /* 100% divide number columns */
max-width: 100%;
width: calc((50rem - 100%) * 1000); /* Replace 50rem with size of .parent when you want switch to happen */
}
The width is calculated as your desired breakpoint minus the width of the parent container. This either generates a negative number and the min-width
is applied, or a large number in which case the max-width
takes over.
If you are using flex-box then width
can also be flex-basis
.
Source: https://www.sitepoint.com/responsive-css-patterns-without-media-queries/
来源:https://stackoverflow.com/questions/56621930/four-column-layout-that-converts-to-single-column-without-media-query