How to Position an Image in CSS?
Overview
The image position in CSS can be changed by using CSS properties like object-position property and float property. Object-position property is used to align the position with respect to the x,y coordinates of the image within its container. The float property is used to float an element inside the container toward the left or right side.
Pre-requisite
You should know how to use CSS properties on elements. This article will explain the object-position property and float property with an example that will be easy to understand.
Syntax
1. object-position property: The Syntax of object position property :
position can be a numerical value that specifies the distance from the left of the content box(i.e x axis) and the distance from the top of the content box (i.e., y-axis). It can also take values like left, right, top, bottom, and initial and inherit them as a string to specify the position.
2. Float property: The Syntax of the float property :
Methods
Method 1: Using object-position Property
object-position property: The object position property is used to position any element within a container to the required position within the container. The < img > element or < video > element are mostly positioned within a container using the object position property.
Syntax
The Syntax for the object position property is
Position can take numerical, specific string values, percentage, length, and edge offsets values. Some values are shown in the examples below.
Example Let's see a simple example of object position property and place the img to the top left of the container.
Output :
Method 2: Using float Property
float property: float property is used to change the image position in CSS to the extreme left or extreme right of the container. Float is used to position an element only horizontally. The Syntax of the float property is as follows:
here,
left: place the element to the extreme left of the container right: place the element to the extreme right of the container inherit: inherits floating property from its parent (div, semantic element, etc.) none: element is displayed at its original position as it is.
Some examples of float properties values are as follows:
Let's take an example in which float property is being used on an actual image :
The output of the above HTML code using the float right property is:
Conclusion
- object-property and float properties are used to position an element inside a container.
- object-position property can be used to change the image position in CSS both horizontally as well as vertically within the container of the image.
- float property can be used to change the image position in CSS horizontally within the container of the image.
- The position property in the object position can take both numerical values as well as some specified string values like left, right, top and bottom.
- Float property takes some specific values like left, right, inherit, and none.