css - 是否可以在不增加大小的情况下在项目中添加间距?
问题描述
我正在尝试在列之间添加空间(位于带有“display:flex;”的容器内),但是例如,如果我为其中任何一个添加边距,假设我有 2 个宽度为 50% 的列。我想到在列之间“添加”一些空间以便它们不会粘在一起的唯一方法是创建另一个容器只是为了添加边距、bg-color、填充等。
基于 12 列的网格示例,其中一切正常:
<!DOCTYPE html>
<html>
<head>
<style>
*,
*::after,
*::before {
margin: 0;
box-sizing: border-box;
}
.row {
display: flex;
flex-flow: row wrap;
}
/* based on 12 columns */
.col-hd-3 {
width: 25%;
}
</style>
</head>
<body>
<div class="row">
<div class="col-hd-3" style="background-color: red;">
test
</div>
<div class="col-hd-3" style="background-color: green;">
test
</div>
<div class="col-hd-3" style="background-color: yellow;">
test
</div>
<div class="col-hd-3" style="background-color: grey;">
test
</div>
</div>
</body>
</html>
现在,假设我向任何列添加边距:
<! ---->
<div class = "row">
<div class = "col-hd-3" style = "background-color: red; margin: 12px;">
test
</ div>
<! ---->
最后一列将转到下一行。
所以解决它的唯一方法是:
<!---->
<div class="row">
<div class="col-hd-3">
<div style="margin: 12px; padding: 5px; background-color: red;">
Test
</div>
</div>
<!---->
我确定解决方案,还是做错了什么?
解决方案
因此,当您使用display: flex
时,您需要在列上设置flex-grow: 1;
andflex-basis: 0;
或简单地设置flex: 1;
. 阅读:https ://www.w3schools.com/cssref/css3_pr_flex.asp
flex-grow
定义了弹性项目在必要时增长的能力,并定义flex-basis
了在剩余空间分配之前元素的默认大小。
所以:
.col-hd-3 {
max-width: 25%; /* COLUMN WILL NOT BE WIDER THAN 25% */
margin: 12px;
flex-basis: 0;
flex-grow: 1;
}
或者您可以使用flex
速记:
.col-hd-3 {
max-width: 25%; /* COLUMN WILL NOT BE WIDER THAN 25% */
margin: 12px;
flex: 1;
}
*,
*::after,
*::before {
margin: 0;
box-sizing: border-box;
}
.row {
display: flex;
flex-flow: row wrap;
}
/* based on 12 columns */
.col-hd-3 {
width: 25%;
margin: 12px;
flex-basis: 0;
flex-grow: 1;
}
<div class="row">
<div class="col-hd-3" style="background-color: red;">
test
</div>
<div class="col-hd-3" style="background-color: green;">
test
</div>
<div class="col-hd-3" style="background-color: yellow;">
test
</div>
<div class="col-hd-3" style="background-color: grey;">
test
</div>
</div>
推荐阅读
- pandas - 查找字段 A 是字段 B 的子字符串的行
- typescript - 在映射类型中只允许一个属性
- postgresql - 在 postgres 中创建新用户并授予权限
- angular - SSR - Angular Universal 9 加载我的根两次并挂起
- angular - Angular Universal 需要 initialNavigation=enabled 这会破坏 APP_INITIALIZER 和 Guards
- c++ - 通过线程间通信将函数传递给 wxWidgets 线程池
- django - 如何在 django 模板的 for 循环中访问单个数据
- r - 为R中列表的向量元素分配名称
- javascript - django模板系统为不同的帖子返回相同的ID
- laravel - Laravel,如何使用相同的类模型在没有硬编码的情况下调用表名?