【问题标题】:Bootstrap 5 squared columnsBootstrap 5平方列
【发布时间】:2022-01-19 19:50:39
【问题描述】:
如何对 .rows 列进行平方(例如 col-sm-4)?
我想把每一列变成 widht = height equal columns。
<div class="row">
<div class="col-sm-4">I'm squared</div>
<div class="col-sm-4">I'm too</div>
<div class="col-sm-4">yes, I'm too</div>
</div>
感谢您的建议。
【问题讨论】:
标签:
css
flexbox
bootstrap-5
【解决方案1】:
Bootstrap 没有开箱即用的列高。列布局网格实际上是flex (See reference)。
扩展引导
要使列具有相同的宽度和高度,选项 1 是添加您自己的 CSS 与 Bootstrap 中出现的相同宽度单位。
例子:
html, body {
height: 100%; /* for test, expand height to allow column height works. */
}
[class^="col-"] {
outline: 1px solid orange;/* for test */
}
.row {
height: 100%; /* expand height to allow column height works. */
}
.row-sm-4 {
align-self: stretch;
height: 33.33333333%;/* same value as width but not exactly same unit in pixels */
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-sm-4 row-sm-4">I'm squared</div>
<div class="col-sm-4 row-sm-4">I'm too</div>
<div class="col-sm-4 row-sm-4">yes, I'm too</div>
</div>
See it in action on jsfiddle
这将使用 width 的相同值,但由于它是百分比 (%),因此每个屏幕尺寸的结果会有所不同,并且可能并不总是正方形。您可能会在 height 属性上使用像素,但它可能没有太大帮助。
网格
选项 2 是使用 CSS grid。
例子:
.grid-column {
outline: 1px solid orange;/* for test */
}
.container-grid {
display: grid;
grid-auto-rows: 1fr;
grid-template-columns: repeat(3, 1fr);
grid-column-gap: 20px;
grid-row-gap: 20px;
}
.container-grid .grid-column {
aspect-ratio: 1;
width: 100%;
}
<div class="container-grid">
<div class="grid-column">I'm squared</div>
<div class="grid-column">I'm too</div>
<div class="grid-column">yes, I'm too</div>
</div>
See it in action
详细了解CSS grid on css tricks website。关于CSSsquare grid的答案。