htmlcssbackground-imagebackground-positionbackground-size

Why background-position with a percentage value does not move the background?


I have an element with a background-image set to a gradient and background-position: 80%; but the background-position does not move the gradient at all.

<div>Hello</div>
div {
    background-image: linear-gradient(120deg, red 0%, red 50%, green 50%);
    background-position : 80%;
}

However if i change the value to a pixel unit number for example 20px, it will move the background toward right side 20 pixels. I want to know why the percentage value does not work ?

background-size solves this problem :

<div>Hello</div>
div {
    background-image: linear-gradient(120deg, red 0%, red 50%, green 50%);
    background-position : 80%;
    background-size: 200%
}

But it makes another question for me that why it moves the background to left ? I expected it to move it to right because the value is positive .


Solution

  • The background-position property in CSS is used to specify the initial position of a background image. When you use a percentage value, it's relative to the size of the container and the size of the background image.

    In your first example, the background-position: 80%; doesn't seem to move the gradient because the size of the gradient is exactly the size of the container. The gradient is created to fit the container, so moving it 80% doesn't change its appearance because it's essentially moving within itself.

    When you add background-size: 200%, you're making the gradient twice as wide as the container. Now, when you set background-position: 80%;, it has an effect because the gradient is larger than the container. The gradient moves, but it might appear to move to the left because you're actually moving the starting point of the image to the right, revealing more of the left side of the image.

    Here's a simplified way to visualize it: