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 .
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:
background-position
is where you align the left edge of the box with the strip of paper.background-position
is 0%
, the left edges align, and you see the left half of the paper in the box.background-position
is 80%
, you're aligning the left edge of the box with a point near the right end of the paper. So, you see the right part of the paper in the box, which makes it look like the paper (gradient) has moved to the left.