CSS object-position property


The object-position Property in CSS

The object-position property in CSS is used to specify the alignment of an element's content within its container. It works in conjunction with the object-fit property, which determines how the content fits within the container. While object-fit controls how the content is resized to fit the container, object-position adjusts the position of the content within the container.

Values of object-position

The object-position property accepts two values: a horizontal position and a vertical position. These values determine where the content should be aligned within the container.

  1. Percentage Values (e.g., 50% 50%)

    • Defines the position of the content as a percentage of the container's width and height.
    • Example: 50% 50% centers the content both horizontally and vertically.
    .centered { object-position: 50% 50%; }
  2. Length Values (e.g., 10px 20px)

    • Specifies exact pixel values or other length units (like em, rem, etc.) for the horizontal and vertical positions.
    • Example: 10px 20px positions the content 10 pixels from the left and 20 pixels from the top of the container.
    .offset { object-position: 10px 20px; }
  3. Keywords (e.g., left, right, top, bottom, center)

    • left top: Aligns the content to the top-left corner of the container.
    • right bottom: Aligns the content to the bottom-right corner of the container.
    • center center: Centers the content both horizontally and vertically.
    .top-left { object-position: left top; } .bottom-right { object-position: right bottom; }
  4. Combination of Keywords and Lengths (e.g., left 10px)

    • Combines keywords with specific length values to fine-tune positioning.
    .left-offset { object-position: left 10px; }

Example

<div class="container"> <img src="example.jpg" alt="Example Image" class="cover"> </div>
.container { width: 300px; height: 200px; overflow: hidden; border: 2px solid #ccc; } img { width: 100%; height: 100%; object-fit: cover; /* Ensures image covers the entire container */ } .cover { object-position: center center; /* Centers the image within the container */ }

Explanation

  • Container: The container has fixed dimensions of 300px by 200px.
  • Image: The object-fit: cover; property ensures that the image covers the entire container. The object-position: center center; property aligns the image to the center of the container.

Use Cases

  • Positioning Media: Control how images and videos are positioned within their containers, especially when using object-fit to resize them.
  • Responsive Design: Adjust content alignment for various screen sizes and container dimensions to maintain visual appeal.
  • Background Images: Fine-tune the position of background images in responsive layouts.