Flex布局之align-self
align-self 允许单个子元素覆盖容器的 align-items 设置,实现独立的交叉轴对齐。
语法
CSS
.item {
align-self: auto | flex-start | flex-end | center | baseline | stretch;
}
属性值说明
| 值 | 说明 |
|---|---|
auto | 继承父元素的 align-items 值(默认) |
flex-start | 交叉轴起点对齐 |
flex-end | 交叉轴终点对齐 |
center | 交叉轴居中对齐 |
baseline | 基线对齐 |
stretch | 拉伸填满交叉轴 |
基本用法
默认对齐 vs 单独控制
CSS
.container {
display: flex;
align-items: stretch; /* 容器默认等高 */
height: 200px;
}
.item {
/* 默认继承 stretch */
}
.item-special {
align-self: center; /* 单独居中对齐 */
}
多种对齐混合
CSS
.container {
display: flex;
height: 150px;
border: 1px solid #ccc;
}
.item-start { align-self: flex-start; }
.item-center { align-self: center; }
.item-end { align-self: flex-end; }
.item-stretch { align-self: stretch; }
HTML
<div class="container">
<div class="item-start">起点对齐</div>
<div class="item-center">居中对齐</div>
<div class="item-end">终点对齐</div>
<div class="item-stretch">拉伸</div>
</div>
常见场景
导航栏图标对齐
CSS
.nav {
display: flex;
align-items: center;
height: 60px;
}
.nav-logo {
align-self: flex-start; /* Logo 顶部对齐 */
}
.nav-menu {
align-self: center; /* 菜单居中 */
}
.nav-action {
align-self: flex-end; /* 操作按钮底部对齐 */
}
卡片底部按钮
CSS
.card {
display: flex;
flex-direction: column;
}
.card-footer {
align-self: flex-end; /* 按钮靠右底部 */
margin-top: auto; /* 推到底部 */
}
单个元素突出
CSS
.toolbar {
display: flex;
align-items: center;
}
.toolbar-title {
align-self: stretch; /* 标题占满高度 */
display: flex;
align-items: center;
}
注意事项
align-self只影响交叉轴对齐(主轴为行时是垂直方向)- 如需控制主轴对齐,使用
justify-self(Grid 支持,Flex 不支持) - 单个元素的
align-self会覆盖容器的align-items
与 align-items 的关系
CSS
/* 容器设置全局对齐 */
.container {
display: flex;
align-items: center; /* 全局居中 */
}
/* 单个元素覆盖 */
.item {
align-self: flex-start; /* 单独顶部对齐 */
}
要点总结
align-self覆盖容器align-items的设置- 常用值:
flex-start、center、flex-end、stretch - 实现单个元素独立对齐,其他元素保持默认
- 交叉轴方向对齐(水平布局时为垂直方向)
📝 发现内容有误?点击此处直接编辑