DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!
CSS 中的 justify-self
属性设置元素在其包含块中的对齐方式。其行为取决于包含块的 display
属性。例如,如果包含块是网格容器(即 display: grid
),我们可以沿着“内联”轴(根据内容的 direction
属性,可以是垂直或水平)对齐其中的元素。
.element {
justify-self: start;
}
justify-self
在 CSS Box Alignment 模块 Level 3 规范 中定义。
让我们谈谈方向
方向在 CSS 中是相对的概念。您可能习惯于根据偏移量来考虑方向,例如 top
、bottom
、left
和 right
。但并非所有语言都采用相同的从左到右 (LTR) 方向。这就是为什么 CSS 越来越重视内容的 逻辑属性(双关语)。
CSS 中的逻辑属性会考虑内容的 direction
、text-orientation
和 writing-mode
属性,然后相应地处理内联和块方向。因此,在从左到右的书写模式下,内联表示左右,块表示上下。在垂直书写模式下,内联表示上下,块表示左右。这就是逻辑属性中的“逻辑”,例如 margin-inline
和 margin-block
等许多其他属性。

-block
,水平轴将后缀为 -inline
,两者后面都跟着 start
或 end
。这与 justify-self
有什么关系?它使用关键字值(例如 start
和 end
),这些值在不同的上下文中含义不同。justify-self
沿内联轴对齐元素,在 LTR 书写模式下该轴为水平方向,但在其他情况下为垂直方向。
语法
justify-self: auto | normal | stretch | <baseline-position> | <overflow-position>? [ <self-position> | left | right ]
值
/* Basic keywords */
justify-self: auto;
justify-self: normal;
justify-self: stretch;
/* Postion keywords */
justify-self: start;
justify-self: end;
justify-self: center;
justify-self: left;
justify-self: right;
justify-self: flex-start;
justify-self: flex-end;
justify-self: self-start;
justify-self: self-end;
/* Baseline keywords */
justify-self: baseline;
justify-self: first-baseline;
justify-self: last-baseline;
/* Overflow keywords */
justify-self: safe center;
justify-self: unsafe center;
/* Global keywords */
justify-self: inherit;
justify-self: initial;
justify-self: unset;
基本关键字值
auto
:默认值。当元素不包含在父元素中时,以及当元素位于绝对定位的父元素内部(即position: absolute
)时,它的行为类似于normal
值。否则,它将继承父元素的justify-items
值,例如当元素位于网格容器中时。normal
:采用包含元素的框的默认对齐方式。因此,根据包含元素的布局模式,它的行为可能会有所不同,无论它是正常的块级布局还是其他布局,例如网格容器。- 块级布局 (
start
) - 网格布局
stretch
- Flexbox (忽略)
- 表格单元格 (忽略)
- 绝对定位布局 (
start
) - 绝对定位框 (
stretch
) - 替换的绝对定位框 (
start
)
- 块级布局 (
stretch
:这将强制元素在包含元素中占据尽可能多的空间,当然,也要考虑容器中的其他项目。它会拉伸多少?这取决于元素本身的计算width
和height
属性,需要将这两个属性设置为auto
才能使此值生效。注意:如果沿对齐轴的任意一个边距设置为auto
,我们将不会得到任何拉伸。
.element {
justify-self: stretch;
}
位置关键字值
start
:元素沿容器的起始边缘“填充”。“填充”的意思是元素的起始边缘与容器的起始边缘对齐,并且元素不会拉伸以填充其余可用空间。end
:元素沿容器的结束边缘“填充”。center
:元素沿对齐轴的中心“填充”。left
:元素沿容器的左边缘“填充”。如果对齐轴为内联,则这实际上与start
相同。right
:元素沿容器的右边缘“填充”。如果对齐轴为内联,则这实际上与end
相同。flex-start
:当元素不是弹性容器中的弹性项目(即未设置为display: flex
的容器)时,此值的行为类似于start
。flex-end
:当元素不是弹性容器中的弹性项目时,此值的行为类似于end
。self-start
:元素沿着其自身的起始边缘排列,这取决于其方向。self-end
:元素沿着其自身的结束边缘排列,这取决于其方向。
.element {
justify-self: start;
}
.element {
justify-self: end;
}
.element {
justify-self: center;
}
基线关键字值
这些将元素的第一个或最后一个基线与对应对齐上下文的基线对齐。
.element {
justify-items: <first | last> baseline;
}
first baseline
的回退对齐方式为safe start
。last baseline
的回退对齐方式为safe end
。- 单独使用
baseline
时,对应于first baseline
。
溢出关键字值
overflow 属性决定了当内容超出网格边界限制时,它将如何显示网格的内容。因此,当内容大于对齐容器时,会导致溢出 这可能会导致数据丢失。为了防止这种情况,我们可以使用 safe
值,它告诉浏览器更改对齐方式,以便不会丢失数据。
safe
:如果元素溢出包含元素,则其行为就像对齐模式为start
一样。unsafe
:无论包含元素的大小如何,都将尊重元素的对齐值,这允许元素在大小超出可用空间时溢出包含元素。