css - 试图用 4 个单元格创建一行
问题描述
我正在尝试用 4 个单元格创建一行,但我不知道它为什么不起作用。
我创建了一个父母row
和 4 个孩子。
<div className='row'>
<div className='col-1-of-4'>
hi
</div>
<div className='col-1-of-4'>
hi
</div>
<div className='col-1-of-4'>
hi
</div>
<div className='col-1-of-4'>
hi
</div>
</div>
(忽略类的类名,因为我正在使用反应)
和CSS属性是:
[class^="col-"] {
float: left;
&:not(:last-child) {
margin-right: $gutter-horizontal;
}
}
.col-1-of-4 {
width: calc((100% - #{$gutter-horizontal}) / 4);
}
它的作用是计算总宽度,然后减去边距,然后除以 4。从技术上讲,它应该可以工作,我应该能够连续看到 4 个单元格。但我得到的结果是,连续 3 个单元格和下一行的第四个单元格。
结果应该是这样的
hi hi hi hi
但实际结果是
hi hi hi
hi
这是工作代码 https://codepen.io/sarmad1995/pen/REYXBV?editors=1100
解决方案
您不应该在计算中划分保证金。它应该在外部,否则您将删除少于为每个元素设置的边距。您正在设置X
边距并且仅删除X/4
,因此每个元素将25% - X/4 + X
(最后一个25% - X/4
)作为一个空间,因此总数将100% + 2X
大于100%
.
.col-1-of-4 {
width: calc(100% / 4 - #{$gutter-horizontal});
}
.row {
max-width: 114rem;
margin: 0 auto;
}
.row:not(:last-child) {
margin-bottom: 8rem;
}
.row::after {
content: "";
display: table;
clear: both;
}
.row [class^="col-"] {
float: left;
}
.row [class^="col-"]:not(:last-child) {
margin-right: 6rem;
}
.row .col-1-of-4 {
width: calc(100% / 4 - 6rem);
background-color: red;
}
<div class='row'>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
</div>
如果您需要行为之间的空间(这是您想要的),您可以这样做:
.col-1-of-4 {
width: calc(100% / 4 - 3*#{$gutter-horizontal}/4);
}
你也可以这样写:
.col-1-of-4 {
width: calc((100% - 3*#{$gutter-horizontal})/4);
}
您需要从总宽度中删除 3 个边距(为前 3 个元素定义),然后除以 4:
.row {
max-width: 114rem;
margin: 0 auto;
}
.row:not(:last-child) {
margin-bottom: 8rem;
}
.row::after {
content: "";
display: table;
clear: both;
}
.row [class^="col-"] {
float: left;
}
.row [class^="col-"]:not(:last-child) {
margin-right: 6rem;
}
.row .col-1-of-4 {
width: calc(100% / 4 - 3*6rem/4);
background-color: red;
}
<div class='row'>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
<div class='col-1-of-4'>
hi
</div>
</div>
您应该对所有其他类应用相同的逻辑
推荐阅读
- c - 为什么当分配看起来合适时指针分配显示左值错误?
- spring-boot - 使用 Testcontainers 执行运行集成测试的 Gitlab CI 管道作业时出现问题
- python - 如何在 Python 中配置装饰器
- kotlin - 如何将数据从电脑上传到firestore。获取“无法检测我们是否在 Google Compute Engine 上运行。”
- r - 将颜色酿造器应用于 ggplot 中的单行
- r - R - 按组计算滞后变量
- api - ActiveMQ Artemis 使用 API 调用浏览方法
- html - 是否可以在 twig Symfony 4 中将 CSS 类添加到 form_row?
- excel - 重命名过滤器值
- python - 如何在熊猫数据框中删除具有特定名称的多行