gpt4 book ai didi

css - 如何创建基于flexbox的网格系统?

转载 作者:太空宇宙 更新时间:2023-11-04 06:31:57 25 4
gpt4 key购买 nike

出于学习的目的,我尝试创建一个基于flexbox的网格系统,但创建后发现了一些问题:当总列占空间的100%时,最后一列到下一行(容器是flex-flow: row wrap;) 但当它们不是 100%(例如,一列占 30%,另一列占 65%)时,它们在同一行上......然后我发现它与边距有关,但仍然我无法解决它。

我现在的疑惑是:列的宽度应该用什么? flex 基础?宽度

如何解决这个边距问题?我在 github 元素中看到一个使用类似“gap”的东西,但我仍然不太明白它是如何工作的......

我尝试将 calc () 属性与 10px 的“- $ gap”一起添加,但我仍然无法按应有的方式生成网格。

我之前的代码是这样的:

.row {
display: flex;
}

@for $i from 1 through $grid-cols {

@media (max-width: 768px) {
.col-mob-#{$i} {
width: 100 / ($grid-cols / $i) * 1%;
}
}

@media (min-width: 769px) and (max-width: 1023px) {
.col-tab-#{$i} {
width: 100 / ($grid-cols / $i) * 1%;
}
}

@media (min-width: 1024px) and (max-width: 1407px) {
.col-hd-#{$i} {
width: 100 / ($grid-cols / $i) * 1%;
}
}

@media (min-width: 1408px) {
.col-fhd-#{$i} {
width: 100 / ($grid-cols / $i) * 1%;
}
}
}

编辑:我设法按照我想要的方式将其保留为以下方式:

$grid-cols: 12;
$gap: 0.75rem !default;

// .row is used as container for divs with columns
.row {
display: flex;
}

@for $i from 1 through $grid-cols {

@media (max-width: 768px) {
.col-mob-#{$i} {
flex-basis: calc((100 / (#{$grid-cols} / #{$i}) * 1%) - #{$gap});
}
}
// ....

最佳答案

FLexbox 是线性的,而 Grid 是二维的。有很多方法可以解决这个问题。但你需要使用 flex-wrap: no-wrap

我会先定义一个 flex 行。

.outerRow {
display: 'flex';
# Do not allow wrap (event though this is default)
flex-wrap: 'no-wrap';
# Fill the full height
align-items: 'stretch';
}

现在是您的专栏。如果您想要两列 25% 和一列 50%,请执行以下操作:

.quarter {
flex-grow: 1;
}
.half {
flex-grow: 2;
}

注意它们是比率。

然后你需要制作列类:

.column {
display: 'flex';
# Make this a flex-column
flex-direction: 'column';
# Do not allow wrap (event though this is default)
flex-wrap: 'no-wrap';
# Fill the full width
align-items: 'stretch';
}

然后在这些列中,您可以进行线性 flex 排列。您可以使用上面的 quarterColumn 或 halfColumn 类......或者您可以像这样编辑类:

.column {
display: 'flex';
flex-direction: 'column';
flex-wrap: 'no-wrap';
# Everything floats to flex-start (event though this is default)
justify-content: 'flex-start';
}

用 block 级元素填充列,并以 pinterest 风格的交错网格结束。

<div class="outerRow">
<div class="quarter column">
<div></div>
<div></div>
<div></div>
</div>
<div class="half column">
<div></div>
<div></div>
<div></div>
</div>
<div class="quarter column">
<div></div>
<div></div>
<div></div>
</div>
</div>

或者如果你想让它们统一:

<div class="outerRow">
<div class="quarter column">
<div class="half"></div>
<div class="half"></div>
<div class="half"></div>
</div>
<div class="half column">
<div class="half"></div>
<div class="half"></div>
<div class="half"></div>
</div>
<div class="quarter column">
<div class="half"></div>
<div class="half"></div>
<div class="half"></div>
</div>
</div>

记住 flex-grow 值是相互之间的比率

阅读https://css-tricks.com/snippets/css/a-guide-to-flexbox/

:)

关于css - 如何创建基于flexbox的网格系统?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com