CSS - object-position Property



Description

The object-position property in CSS is used to specify the position of the content inside an element that has a defined size. It is commonly used with images or videos, allowing you to control where the focal point of the object should appear within its container.

Possible Values

Can take one to four values that specify the 2D position of the element

  • keyword values:

    • top: Example − object-position: top;

    • bottom: Example − object-position: bottom;

    • left: Example − object-position: left;

    • right: Example − object-position: right;

    • center: Example − object-position: center;

  • <percentage>: Sets the position based on any percentage value which is relative to the element. Example − object-position: 50% 75%;

  • <length>: Sets the position based on any length value. Example − object-position: 2cm 4cm;

  • edge offsets values: Consists of four values. Example − object-position: top 20px right 10px;

Applies to

Replaced elements, such as images, videos, etc.

DOM Syntax

object.style.objectPosition = "<position> | 50% 50%";

Example

Here is an example:

<html>
<head>
<style>
   img {
      width: 300px;
      height: 250px;
      border: 1px solid black;
      background-color: silver;
      margin-right: 1em;
      object-fit: none;
   }

   #obj-pos-1 {
      object-position: 20px;
   }

   #obj-pos-2 {
      object-position: 50% 10%;
   }

   #obj-pos-3 {
      object-position: right 2em left 20px ;
   }
</style>
</head>
<body>
   <img id="obj-pos-1" src="images/orange-flower.jpg" alt="Object position single" />
   <img id="obj-pos-2" src="images/orange-flower.jpg" alt="Object position percent" />
   <img id="obj-pos-3" src="images/orange-flower.jpg" alt="Object position four" />
</body>
</html>
Advertisements