CSS object-position property (Image Sizing)
The CSS object-position
property is used to specify how an <img> or <video> should be positioned within its container.
The Image
Look at the following image from Forest, which is 400x250 pixels:
Next, we use object-fit: cover;
to keep the aspect ratio and to fill the given dimension. However, the image will be clipped to fit, like this:
Example
img {
width: 200px;
height: 250px;
object-fit: cover;
}
width: 200px;
height: 250px;
object-fit: cover;
}
Using the object-position Property
Let's say that the part of the image that is shown, is not positioned as we want. To position the image, we will use the object-position
property.
CSS Syntax
object-position: position|initial|inherit;
Property Values
Value | Description |
---|---|
position | Specifies the position of the image or video inside its content box. First value controls the x-axis and the second value controls the y-axis. Can be a string (left, center or right), or a number (in px or %). Negative values are allowed |
initial | Sets this property to its default value. |
inherit | Inherits this property from its parent element. |
Here we will use the object-position
property to position the image so that the black trees is in center:
Example
img {
width: 200px;
height: 250px;
object-fit: cover;
object-position: 0% 100%;
}
width: 200px;
height: 250px;
object-fit: cover;
object-position: 0% 100%;
}
Here we will use the object-position
property to position the image so that the river is in center:
Example
img {
width: 200px;
height: 250px;
object-fit: cover;
object-position: 100% 0%;
}
width: 200px;
height: 250px;
object-fit: cover;
object-position: 100% 0%;
}
CSS Object-* Properties
The following table lists the CSS object-* properties:
Property | Description |
---|---|
object-fit | Specifies how an <img> or <video> should be resized to fit its container |
object-posititon | Specifies how an <img> or <video> should be positioned with x/y coordinates inside its "own content box" |
Comments
Post a Comment