CSS

background-position


The background-position property in CSS is used to specify the initial position of a background image within an element. You can control where the background image starts from using various units and keywords.

 

Values for background-position

Keywords: These are the predefined values that specify the position of the background image.

  • left top
  • left center
  • left bottom
  • right top
  • right center
  • right bottom
  • center top
  • center center (or just center)
  • center bottom

1. Length Values:

You can use specific lengths (e.g., pixels, ems) to position the background image.

.example2 {
    background-image: url('background.png');
    background-position: 50px 100px;
}

 

2. Percentage Values 

.example3 {
    background-image: url('background.png');
    background-position: 50% 50%; /* Center of the element */
}

 

3. Combination of Length and Percentage

.example4 {
    background-image: url('background.png');
    background-position: 10px 50%;
}

 

Example 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Background Position Example</title>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        h2 {
            margin-top: 20px;
        }
        .position-example {
            width: 300px;
            height: 200px;
            background-image: url('background.png');
            background-repeat: no-repeat;
            border: 1px solid #000;
        }
    </style>
</head>
<body>
    <h2>Left Top</h2>
    <div class="position-example" style="background-position: left top;"></div>

    <h2>Center</h2>
    <div class="position-example" style="background-position: center;"></div>

    <h2>Right Bottom</h2>
    <div class="position-example" style="background-position: right bottom;"></div>

    <h2>50% 50%</h2>
    <div class="position-example" style="background-position: 50% 50%;"></div>

    <h2>10px 50%</h2>
    <div class="position-example" style="background-position: 10px 50%;"></div>

    <h2>50px 100px</h2>
    <div class="position-example" style="background-position: 50px 100px;"></div>
</body>
</html>