CSS `object-position`: Precisely Positioning Content within Containers

Learn how to use the CSS `object-position` property to precisely control the alignment of content (images, videos, etc.) within its container. This tutorial explains its syntax, demonstrates its use with different units and keywords, and shows how it works in conjunction with `object-fit` for creating customized and responsive layouts.



Understanding the CSS `object-position` Property

This CSS property controls how content is aligned within its container. It works best with the object-fit property to position elements like images or videos using x and y coordinates.

Default Positioning

By default, object-position is set to 50% 50%, meaning images are centered within their containers.

Syntax and Values

The object-position property's syntax is straightforward:

object-position: position | inherit | initial;

`position` Value

This defines the position of the image or video. It accepts:

  • Two numerical values (e.g., 0 10px): The first controls the x-axis (horizontal), the second the y-axis (vertical).
  • Percentages (e.g., 25% 75%)
  • Keywords like left, right, top, bottom, center (e.g., right top).

Negative values are allowed. The default is 50% 50% (center).

`inherit` Value

Inherits the object-position value from its parent element.

`initial` Value

Resets the property to its default value (50% 50%).

Examples

Let's explore some examples to illustrate how object-position works. (Note: The "Test it Now" links are placeholders and would typically link to interactive examples.)

Example 1: Using Pixel Values

object-position: 90px 200px

Test it Now

Example 2: Using Keywords - "center top"

object-position: center top

Test it Now

Example 3: Using Keywords - "right top"

object-position: right top

Test it Now

Example 4: Using Keywords - "left top"

object-position: left top

Test it Now

Example 5: Using "initial"

object-position: initial (This will center the image)

Test it Now