CSS object-position 属性


目录

    显示目录


CSS object-position 属性 用于指定 <img> 或 <video> 应如何定位 在其容器内。


图片

看下面这张来自巴黎的图片,像素为 400x300:

Paris

接下来,我们使用 CSS 属性

object-fit: cover;

用于保持纵横比并填充给定的尺寸。但是,图像将被裁剪以适合,如下所示:

Paris

例子

img {
  width: 200px;
  height: 
  300px;
  object-fit: cover;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
img {
  width: 200px;
  height: 300px;
  object-fit: cover;
}
</style>
</head>
<body>

<h2>Using object-fit: cover</h2>

<img src="paris.jpg" alt="Paris" width="400" height="300">

</body>
</html>




使用对象位置属性

假设图像中显示的部分没有按照我们想要的方式放置。为了定位图像,我们将使用 object-position 属性。

在这里,我们将使用 object-position 属性来定位图像,使伟大的老建筑位于中心:

Paris

例子

img {
  width: 200px;
  height: 
  300px;
  object-fit: cover;
  object-position: 80% 100%;
}

自己尝试一下 →

<!DOCTYPE html>
<html>
<head>
<style>
img {
  width: 200px;
  height: 300px;
  object-fit: cover;
  object-position: 80% 100%;
}
</style>
</head>
<body>

<h2>Using object-position</h2>

<p>Here we will use the object-position property to position the image so that the great old building is in center:</p>

<img src="paris.jpg" alt="Paris" width="400" height="300">

</body>
</html>


在这里,我们将使用 object-position 属性来定位图像,使著名的埃菲尔铁塔位于中心:

Paris

例子

img {
  width: 200px;
  height: 
  300px;
  object-fit: cover;
  object-position: 15% 100%;
}

自己尝试一下→

<!DOCTYPE html>
<html>
<head>
<style>
img {
  width: 200px;
  height: 300px;
  object-fit: cover;
  object-position: 15% 100%;
}
</style>
</head>
<body>

<h2>Using object-position</h2>

<p>Here we will use the object-position property to position the image so that the famous Eiffel Tower is in center:</p>

<img src="paris.jpg" alt="Paris" width="400" height="300">

</body>
</html>



CSS 对象-* 属性

下表列出了 CSS object-* 属性:

object-fit

指定如何调整 <img> 或 <video> 的大小以适合其容器

object-position

指定如何使用 x/y 定位 <img> 或 <video> 其“自己的内容框”内的坐标