CSS background-position and image size

2015-Aug-09 17:43

Say you have a page with two parts, left and right, and you want to put the image only in the right part. For simplicity, let's use gradients, which are behaving as images. In this case, you need to know where the image starts. If you choose to use percentages, the right part would start at 50% and the width should also be 50%. That means you would naturally write a CSS such as like:

Oops... As you see, that did not really behave as we wanted. Instead of occupying the right part, it occupies 25% on each side of the center line.

To see what's going on, we can check the CSS3 backgrounds specification the background-position percentages are dependent on the image size:

Percentages: refer to size of background positioning area minus size of background image; see text

This example makes it a bit clearer what's happening:

In order to make it work with percentages, a simple formula can be used:

p = 100 * l * (100 - w)

where p is what should be used in background-position property, l is the desired percentage from the left and w is the width of the image in percentages. Same would work for top / height. Here are two examples, the first with values put as-is and the second with values calculated as per above: