四列布局,无需媒体查询即可转换为单列 [英] Four Column Layout that Converts to Single Column without Media Query
问题描述
我正在尝试创建四列布局,其中每一列都会随着窗口的大小而增长和收缩,但是每一列都具有最小宽度,并且当窗口对于所有四列而言都太小而无法容纳在一行中时,它将转换为单列,每个部分占据整个宽度.
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.
我无法使用flex-box或CSS网格来做到这一点.我想在没有媒体查询的情况下执行此操作.使用媒体查询可以很轻松地解决此问题,但是我不喜欢它们!
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>
还有一个Codepen: https://codepen.io/WriterState/pen/oRKxMj
And a codepen: https://codepen.io/WriterState/pen/oRKxMj
推荐答案
Media queries are great, but they are not always a viable substitute for container queries (which sadly do not exist).
当您知道将有多少列时,可以使用CSS calc
实现水平到垂直的布局切换.
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 */
}
宽度的计算方法是所需的断点减去父容器的宽度.这将生成一个负数并应用 min-width
,或者在此情况下使用较大的数字 max-width
来代替.
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.
如果您使用的是flex-box,则 width
也可以是 flex-basis
.
If you are using flex-box then width
can also be flex-basis
.
来源: https://www.sitepoint.com/响应式CSS样式,无媒体查询/
这篇关于四列布局,无需媒体查询即可转换为单列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!