Introduction to CSS object-postion
CSS The object-position Property
The object-position
property in CSS specifies the position of an element such as an image, with respect to the containing element. It is often used in conjunction with object-fit
to control the way an image is displayed in its containing element.
The syntax for object-position
is as follows:
object-position: x-position y-position;
Where:
x-position
andy-position
are length, percentage, or keyword values.- The default value is
50% 50%
, which centers the image in its containing element.
As an example
<!DOCTYPE html>
<html>
<head>
<title>Object Position Example</title>
<style>
.container {
width: 400px;
height: 400px;
border: 1px solid black;
position: relative;
overflow: hidden;
}
.image {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
object-fit: cover;
object-position: 30% 20%;
}
</style>
</head>
<body>
<h1>Object Position Example</h1>
<div class="container">
<img
src="https://via.placeholder.com/800x800"
alt="Image"
class="image"
/>
</div>
</body>
</html>
CSS Object-* Properties
CSS Object-* Properties are a set of properties that control how images or other replaced content (such as videos or iframes) are displayed within their containers.
There are four main CSS Object-_ Properties:
The object-fit
This property determines how the image fits into its container. It has five possible values: fill
, contain
, cover
, scale-down
, and none
. fill stretches the image to fill the container, contain scales the image to fit inside the container while maintaining its aspect ratio, cover scales the image to cover the container while maintaining its aspect ratio, scale-down scales the image down if it's larger than the container, and none displays the image at its original size.
The object-position
This property determines where the image is positioned within its container. It takes two values, one for the horizontal and one for the vertical position, which can be specified in pixels, percentages, or keywords.
The object-fit: auto
and object-position: auto
These two properties allow the browser to choose the best fit and position for the image based on its intrinsic dimensions and the size of its container.
The object-clip
This property determines which parts of the image are visible within its container. It has four possible values: border-box
, padding-box
, content-box
, and initial. border-box
clips the image to the container's border, padding-box
clips the image to the container's padding, and content-box
clips the image to the container's content. The initial value resets the property to its default value.