css - 应用“align-self:center”时,Flex 孩子会缩小
问题描述
我想水平居中对齐 flex 容器内的 flex 子项。
但是,当孩子得到align-self: center
它时,它会缩小到宽度 = 0。
请注意,容器和孩子都有max-width
.
你会如何解决这个问题?
.container {
display: flex;
flex-direction: column;
max-width: 400px;
outline: 2px solid red;
}
.child {
display: flex;
flex-direction: column;
max-width: 200px;
height: 50px;
background-color: #ccc;
/* This causing the child to shrink to width = 0 */
/* align-self: center; */
}
<div class="container">
<div class="child">
</div>
</div>
解决方案
问题是stretch
您通过更改元素的对齐方式禁用的效果。默认情况下align-items
设置为stretch
因此元素将尝试填充其父宽度(或行方向的高度)。
您可以使用width:100%
.container {
display: flex;
flex-direction: column;
max-width: 400px;
outline: 2px solid red;
}
.child {
display: flex;
flex-direction: column;
max-width: 200px;
height: 50px;
width:100%;
background-color: #ccc;
align-self: center;
}
<div class="container">
<div class="child">
</div>
</div>
align-items
设置所有弹性容器项目的默认对齐方式,包括匿名弹性项目。align-self
允许为单个弹性项目覆盖此默认对齐方式。参考
推荐阅读
- r - 评估 data.table 中的公式对象
- c# - 动态变量名访问?
- sql - 有没有办法在不使用外键关系的情况下连接 oracle 数据库(或任何数据库)中的两个或多个表?
- django - 如何在 django 注释中从 0 开始计数?
- ajax - 表数据不显示消息没有可用的数据
- python-3.x - 使用 Countvectorizer 获取单个单词的计数,而无需创建整个矩阵
- visual-studio-code - 为什么 VS Code C++ 说没有指定路径?
- django - 两个 Serializers.py 相互导入
- r - R语言Mersenne Twister算法
- powershell - VS Code 终端:清除的代码不断重现