Patterns
CSS object-position
Positioning Images in CSS
CSS object-position aligns images within containers for precise display.
Introduction to CSS object-position
The object-position
property in CSS specifies the alignment of the content of a replaced element within its container. This property is particularly useful when working with images, videos, or other media elements within a container, allowing developers to control how these elements are positioned within their allocated space.
By default, objects are placed at the top left corner of their containers, but with object-position
, you can move them to any part of the container, including the center, bottom, or any specific coordinates using percentage or length values.
Syntax of object-position
The syntax for the object-position
property is straightforward. It accepts one or two values, which can be keywords, percentages, or lengths:
- Keywords: Use
left
,center
,right
,top
,bottom
, orcenter
. - Percentages: Specify horizontal and vertical positions using percentages.
- Lengths: Use specific units like
px
,em
, etc.
Here is the basic syntax:
Using Keywords for Positioning
When using keywords, you can specify the alignment of an object within its container. Here are some examples:
object-position: center center;
- Centers the object both horizontally and vertically.object-position: right bottom;
- Positions the object at the bottom right corner.
Example:
Positioning with Percentages and Lengths
You can gain finer control over the positioning by using percentages or lengths. This is particularly useful for more precise alignment needs.
object-position: 25% 75%;
- Places the object 25% across from the left and 75% down from the top.object-position: 10px 20px;
- Positions the object 10 pixels from the left and 20 pixels from the top.
Example:
Combining object-position with object-fit
The object-position
property is often used in conjunction with object-fit
to control how an image or video fills its container. While object-fit
determines the size, object-position
defines the position.
For example, if an image is set to object-fit: cover;
and you want it centered, you can use object-position: center;
.
Example:
Browser Support for object-position
The object-position
property is well-supported across all modern browsers, including Chrome, Firefox, Safari, Edge, and Opera. However, always consider checking specific versions if you are supporting older browsers.
For the most up-to-date browser compatibility, refer to resources like MDN or Can I Use.
Patterns
- Previous
- User Interface
- Next
- Masking