object-position
object-position CSS 属性指定了所选替换元素内容在其元素框中的对齐方式。未被替换元素对象覆盖的框区域将显示元素的背景。
你可以使用 object-fit 属性来调整替换元素对象的固有大小(即其自然大小)以适应元素框的方式。
试一试
object-position: 50% 50%;
object-position: right top;
object-position: left bottom;
object-position: 250px 125px;
<section id="default-example">
<img
class="transition-all"
id="example-element"
src="/shared-assets/images/examples/moon.jpg" />
</section>
#example-element {
height: 250px;
width: 250px;
object-fit: none;
border: 1px solid red;
}
语法
css
/* Keyword values */
object-position: top;
object-position: bottom;
object-position: left;
object-position: right;
object-position: center;
/* <percentage> values */
object-position: 25% 75%;
/* <length> values */
object-position: 0 0;
object-position: 1cm 2cm;
object-position: 10ch 8em;
/* Edge offsets values */
object-position: bottom 10px right 20px;
object-position: right 3em bottom 10px;
object-position: top 0 right 10px;
/* Global values */
object-position: inherit;
object-position: initial;
object-position: revert;
object-position: revert-layer;
object-position: unset;
值
<position>-
一到四个值,定义了元素的二维位置。可以使用相对或绝对偏移量。
注意: 可以设置位置,使替换元素绘制在其框的外部。
正式定义
正式语法
object-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>
示例
定位图像内容
HTML
在这里我们看到包含两个 <img> 元素的 HTML,每个都显示 MDN 标志。
html
<img id="object-position-1" src="mdn.svg" alt="MDN Logo" />
<img id="object-position-2" src="mdn.svg" alt="MDN Logo" />
CSS
CSS 包含 <img> 元素本身的默认样式,以及两个图像的单独样式。
css
img {
width: 300px;
height: 250px;
border: 1px solid black;
background-color: silver;
margin-right: 1em;
object-fit: none;
}
#object-position-1 {
object-position: 10px;
}
#object-position-2 {
object-position: 100% 10%;
}
第一个图像的位置是其左边缘距离元素框左边缘内缩 10 像素。第二个图像的位置是其右边缘与元素框右边缘齐平,并且位于元素框高度的 10% 处。
结果
规范
| 规范 |
|---|
| CSS 图像模块第三级 # the-object-position |
浏览器兼容性
加载中…
另见
- 其他与图像相关的 CSS 属性:
object-fit、image-orientation、image-rendering、image-resolution。