CSS object-position
The object-position
property in CSS specifies the alignment of an image or video within its container. It works in conjunction with the object-fit
property, determining how the content is positioned when it's scaled or cropped.
Key Topics
Default Position
By default, the object-position
is set to 50% 50%
, centering the content within the container.
<style>
.default-position {
width: 300px;
height: 200px;
object-fit: cover;
object-position: 50% 50%;
}
</style>
<img src="example.jpg" alt="Example" class="default-position">
Explanation: The content is centered both horizontally and vertically within the container by default.
Custom Position
You can customize the position of the content using values like top
, left
, or percentages.
<style>
.custom-position {
width: 300px;
height: 200px;
object-fit: cover;
object-position: top left;
}
</style>
<img src="example.jpg" alt="Example" class="custom-position">
Explanation: The content is aligned to the top-left corner of the container, cropping the bottom and right parts as necessary.
Object Position with Object Fit
The object-position
property works with object-fit
to fine-tune the alignment of scaled or cropped content.
<style>
.position-with-fit {
width: 300px;
height: 200px;
object-fit: contain;
object-position: bottom right;
background-color: #f0f0f0;
}
</style>
<img src="example.jpg" alt="Example" class="position-with-fit">
Explanation: The content is aligned to the bottom-right corner while fitting entirely within the container.
Key Takeaways
- Default Position: By default, content is centered within the container using
50% 50%
. - Custom Positioning: Use keywords like
top
,left
, or percentage values to customize alignment. - Combination with Object Fit: Pair
object-position
withobject-fit
to control both scaling and alignment. - Practical Use: Ideal for cropping or positioning content dynamically in responsive designs.