In this section, we will learn what the object-position property is and how to use it in CSS.
How to Center an Image in CSS: CSS object-position Property Definition and Usage
The CSS `object-position` property is used to set the content position for elements like <iframe>, <img>, <embed>, and <video>.
CSS object-position Property Syntax
object-position: Horizontal-position Vertical-position;
CSS object-position Property Value
Horizontal-Position: The first value of this property defines the horizontal position of the content within its container box. This value can be either (Left, Right, Center) or any number with CSS supported units.
Vertical-Position: The second value of this property defines the vertical position of the content within its container box. This value can be either (Top, Center, Bottom) or any number with CSS supported units.
Notes:
- The position (0,0) is equal to left top corner of the target container element.
- The two global values, “initial” and “inherit” can also be used for this property.
Example: center an image CSS
See the Pen center an image CSS by Enjoy Tutorials (@enjoytutorials) on CodePen.
How Does CSS object-position Property Work?
In this example, the value of the object-position is set to “center” which basically means horizontally and vertically the target image should be centered in its container element.
That’s how this image is centered in its container element.
Example: center align an image
See the Pen center align an image by Enjoy Tutorials (@enjoytutorials) on CodePen.
This time, the image is just horizontally centered in its container, but vertically it is set to the top of the container (because of the value “top”).
Example: CSS position an image
See the Pen CSS position an image by Enjoy Tutorials (@enjoytutorials) on CodePen.