What is object-position in CSS: Definition and Usage
object-position in CSS sets the alignment of replaced elements like images or videos inside their container when the content is smaller or cropped. It works together with object-fit to control which part of the content is visible and where it sits inside the box.How It Works
Imagine you have a photo inside a frame that is smaller than the photo itself. The object-position property tells the browser which part of the photo to show inside that frame. For example, you can show the center, top-left corner, or any other position.
This property works only on replaced elements like images, videos, or canvas, and only when object-fit is set to something that crops or resizes the content (like cover or contain). It uses two values: horizontal and vertical positions, which can be keywords like center, top, or percentages like 20% 80%.
Think of it like moving a picture inside a window to focus on the part you want to show.
Example
This example shows an image inside a 200x200 pixel box. The image is larger and cropped using object-fit: cover. The object-position moves the visible part to the top right corner.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>object-position Example</title> <style> .frame { width: 200px; height: 200px; border: 2px solid #333; overflow: hidden; } img { width: 100%; height: 100%; object-fit: cover; object-position: top right; } </style> </head> <body> <div class="frame"> <img src="https://via.placeholder.com/400x300" alt="Example Image"> </div> </body> </html>
When to Use
Use object-position when you want to control which part of an image or video is visible inside a container that crops or resizes it. For example, if you have a profile picture frame and want to focus on the person's face instead of the center, you can adjust object-position.
It is helpful in responsive designs where images need to fit different box sizes but keep important parts visible. It also works well for video thumbnails or any media where cropping happens.
Key Points
object-positionsets the visible part of replaced elements inside their container.- It works only when
object-fitchanges the default sizing (likecoverorcontain). - Values can be keywords (
center,top,left) or percentages. - Helps focus on important parts of images or videos when cropped.
- Does not affect non-replaced elements like divs or paragraphs.
Key Takeaways
object-position controls which part of an image or video is shown inside a cropped or resized container.object-fit is set to crop or contain the content.