Skip to content
Related Articles

Related Articles

Improve Article

How to set position of an image in CSS ?

  • Last Updated : 13 Jul, 2021
Geek Week

You can easily position an image by using the object-position property. You can also use a bunch of other ways like float-property that will be discussed further in this article.

Methods:

  • object-position property: Specify how an image element is positioned with x, y coordinates inside its content box.
  • float property: Specify how an element should float and place an element on its container’s right or left side.

Method 1: Using object-position Property

Syntax:

object-position: <position>

 



Property values:

  • position: It takes 2 numerical values corresponding to the distance from the left of the content-box (x-axis) and the distance from the top of the content-box (y-axis) respectively.

Note:

  • We can align elements using position property with some helper property left | right | top | bottom.
  • You can either use string values like right, left, center, top, or you can use numerical value in pixel like 200px, 250px.

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        #object1 {
            width: 500px;
            height: 200px;
            background-color: green;
            object-fit: none;
            object-position: center top;
            /* String value */
        }
  
        #object2 {
            width: 500px;
            height: 200px;
            background-color: green;
            object-fit: none;
            object-position: 50px 30px;
            /* Numeric value */
        }
    </style>
</head>
  
<body>
    <center>
        <h2 style="color:green">
            GeeksforGeeks
        </h2>
        <h4>object-position Property</h4>
        <img id="object1"
            src=
  
        <img id="object2"
            src=
    </center>
</body>
  
</html>

Output:

object-position

Method 2: Using float Property

Syntax:

float: none|inherit|left|right|initial;

Note: Elements are floated only horizontally i.e. left or right

Property Value:

  • left: Place an element on its container’s right.
  • right: Place an element on its container’s left.
  • inherit: Element inherits floating property from it’s parent (div, table etc…) elements.
  • none: Element is displayed as it is (Default).

Example:

HTML




<!DOCTYPE html>
<html>
  
<head>
    <style>
        #object1 {
            width: 300px;
            height: 200px;
            float: right;
        }
  
        center {
            width: 500px;
            height: 500px;
            background-color: green;
        }
    </style>
</head>
  
<body>
    <center>
        <h2 style="color:green">
            GeeksforGeeks
        </h2>
        <h4>Float Property</h4>
        <img id="object1"
            src=
    </center>
</body>
  
</html>

Output:

Float property




My Personal Notes arrow_drop_up
Recommended Articles
Page :