object-position
Definition
The object-position property is used to control the position of an image or video inside its container when the container has a different aspect ratio than the content. It allows you to specify the horizontal and vertical position of the content within the container.
Examples
This example centers an image inside its container using object-position: center:
<div class="container">
<img src="image.jpg" alt="Image" class="image">
</div>
.container {
width: 400px;
height: 200px;
overflow: hidden;
}
.image {
width: 100%;
height: 100%;
object-fit: cover;
object-position: center;
}
This example positions an image in the top left corner of its container using object-position: top left:
<div class="container">
<img src="image.jpg" alt="Image" class="image">
</div>
.container {
width: 400px;
height: 200px;
overflow: hidden;
}
.image {
width: 100%;
height: 100%;
object-fit: cover;
object-position: top left;
}
This example positions an image in the bottom right corner of its container using object-position: bottom right:
<div class="container">
<img src="image.jpg" alt="Image" class="image">
</div>
.container {
width: 400px;
height: 200px;
overflow: hidden;
}
.image {
width: 100%;
height: 100%;
object-fit: cover;
object-position: bottom right;
}
Values
Value | Description |
---|---|
left | Align the contents with the left edge of the container |
center | Center the contents horizontally and vertically within the container |
right | Align the contents with the right edge of the container |
top | Align the contents with the top edge of the container |
bottom | Align the contents with the bottom edge of the container |
top left | Position the contents in the top left corner of the container |
top center | Position the contents in the top center of the container |
top right | Position the contents in the top right corner of the container |
center left | Position the contents in the center left of the container |
center right | Position the contents in the center right of the container |
bottom left | Position the contents in the bottom left corner of the container |
bottom center Position the contents in the bottom center of the container | |
bottom right | Position the contents in the bottom right corner of the container |
Best Practices
- Use object-position in conjunction with object-fit to control the position of the contents within the container.
- Avoid using negative values for object-position, as this can cause the contents to be partially or completely hidden.
- Test your layout on different devices and screen sizes to ensure that the positioning works well across a range of devices.
- Be mindful of the aspect ratio of the container and the content. If the aspect ratios are vastly different, the contents may be distorted or cropped in unexpected ways.
Browser Compatibility
Chrome | Firefox | Safari | Internet Explorer | Microsoft Edge | Opera |
---|---|---|---|---|---|
Yes | Yes | Yes | No | Yes | Yes |