Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

background-position: place the image, not the element

Use coordinates, edge offsets and percentages of the space left after sizing the background.

Version: CSS Modules

Syntax

background-position: right 10px bottom 5px;

background-position places each background image after background-size has determined its dimensions. The reference area comes from background-origin, initially padding-box. The initial position is 0% 0%. With two lengths or percentages, the first is horizontal and the second vertical; one value leaves the other axis centered. A pair of suitable keywords can be reordered, but mixed numeric syntax cannot be rearranged arbitrarily. Three- or four-value forms attach offsets to explicit edges, as in right 10px bottom 5px.

A percentage is not simply a fraction of the container width or height. The offset on an axis is the percentage multiplied by the difference (positioning-area size − image size). Thus 50% aligns their centers. If the sizes match, that difference is zero; if the image is larger, it is negative. Length offsets and calc() can still move an equally sized image. Background positioning does not move the element or reserve layout space. Repetition is a separate choice; comma-separated positions map to image layers and shorter lists repeat.

The example paints a 40×20px red image in a 200×100px box without repetition. At 25% 75%, its top-left corner is 40,60: 25% of 160 and 75% of 80. right 10px bottom 5px puts it at 150,75, leaving the requested gaps at the far edges. A third image is 200×100px, exactly the box size; 75% 25% still starts at 0,0. Console output shows actual dimensions, while the PNG checks confirm the three painted rectangles rather than merely accepting the CSS syntax.

Examples

const cases=[['25% 75%','40px 20px'],['right 10px bottom 5px','40px 20px'],['75% 25%','200px 100px']];
cases.forEach(([position,size],i)=>{
  const box=document.createElement('div');box.id='position-'+i;
  box.style.cssText='position:absolute;top:0;width:200px;height:100px;background-image:linear-gradient(red,red);background-repeat:no-repeat';
  box.style.left=(i*220)+'px';box.style.backgroundSize=size;box.style.backgroundPosition=position;document.body.append(box);
  console.log(i+': '+getComputedStyle(box).backgroundSize+'; box='+box.offsetWidth+'x'+box.offsetHeight);
});

Result

0: 40px 20px; box=200x100
1: 40px 20px; box=200x100
2: 200px 100px; box=200x100

Executed in Chromium 157.0.8103.51 with hard-edged local gradients and pixel measurements at device pixel ratio 1. Oversized images, negative percentages, repeated tiles and fixed attachment are explained where relevant but are not additional executions in this example.

Sources