<position>

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

<position> CSS 数据类型表示一个二维坐标,用于设置相对于元素框的位置。它用于 background-positionobject-positionmask-positionoffset-positionoffset-anchortransform-origin 属性。

注意: <position> 值描述的最终位置不必在元素框内部。

语法

Grid showing placement of various values. 0 0 is the top left corner. The four values, right, right center, center left 100%, and top 50% left 100%, are all equivalent, being on the right edge in the middle vertically. The two values, top 75px left 100px and left 100px top 75px, are the same. Bottom left 25% is the same as top 100% left 25%.

<position> 数据类型由一个或两个关键字以及可选的偏移量指定。

关键字值包括 centertoprightbottomleft。每个关键字代表元素框的一条边或两条边之间的中心线。根据上下文,center 代表左右边缘之间的中心,或上下边缘之间的中心。

如果指定了偏移量,它可以是相对的 <percentage> 值或绝对的 <length> 值。正值向右或向下偏移(视情况而定)。负值向相反方向偏移。

如果只指定了一个偏移量,它定义了 x 坐标,另一个轴的值默认为 center

css
/* 1-value syntax */
keyword                  /* Either the horizontal or vertical position; the other axis defaults to center */
value                    /* The position on the x-axis; the y-axis defaults to 50% */

/* 2-value syntax */
keyword keyword          /* A keyword for each direction (the order is irrelevant) */
keyword value            /* A keyword for horizontal position, value for vertical position */
value keyword            /* A value for horizontal position, keyword for vertical position */
value value              /* A value for each direction (horizontal then vertical) */

/* 4-value syntax */
keyword value keyword value /* Each value is an offset from the keyword that precedes it */

注意: background-position 属性还接受三值语法。这在其他使用 <position> 的属性中是不允许的。

插值

动画时,点的横坐标和纵坐标值是独立插值的。但是,由于插值速度由两个坐标的单个 缓动函数 决定,因此点将沿直线移动。

正式语法

<position> = 
<position-one> |
<position-two> |
<position-four>

<position-one> =
left |
center |
right |
top |
bottom |
x-start |
x-end |
y-start |
y-end |
block-start |
block-end |
inline-start |
inline-end |
<length-percentage>

<position-two> =
[ left | center | right | x-start | x-end ] && [ top | center | bottom | y-start | y-end ] |
[ left | center | right | x-start | x-end | <length-percentage> ] [ top | center | bottom | y-start | y-end | <length-percentage> ] |
[ block-start | center | block-end ] && [ inline-start | center | inline-end ] |
[ start | center | end ]{2}

<position-four> =
[ [ left | right | x-start | x-end ] <length-percentage> ] && [ [ top | bottom | y-start | y-end ] <length-percentage> ] |
[ [ block-start | block-end ] <length-percentage> ] && [ [ inline-start | inline-end ] <length-percentage> ] |
[ [ start | end ] <length-percentage> ]{2}

<length-percentage> =
<length> |
<percentage>

示例

有效位置

center
left
center top

right 8.5%
bottom 12vmin right -6px

10% 20%
8rem 14px

无效位置

left right
bottom top
10px 15px 20px 15px

规范

规范
CSS 值和单位模块第 4 级
# position

浏览器兼容性

另见