Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / CSS

translateX(): horizontal movement and the percentage reference

Move the painted box along X while distinguishing its own reference width from the parent width.

Version: CSS Modules

Syntax

transform: translateX(<length-percentage>);

Within transform, translateX() adds a horizontal displacement without changing the Y coordinate. Positive values move along positive X and negative values in the opposite direction; in the ordinary unrotated page this means right and left. Use a length, a percentage or a compatible calc() expression. A nonzero unitless number such as 20 is invalid, while 0 is allowed. The separate translate property is another notation, not the same declaration.

A percentage refers to the width selected by transform-box, not automatically to the parent. For an ordinary HTML box, border-box includes padding and borders, whereas content-box uses the content width. Pure translation does not change dimensions or reserve a new place in normal flow. When combined with scaling or rotation, function order matters; the reference origin also matters to those other transformations.

The measured box has 80px of content plus 10px padding and 5px border on each side: 110px overall, inside a 500px parent. translateX(50%) moves it 55px with border-box and 40px with content-box. A -20px value moves it left; calc(50% - 5px) produces 35px with content-box. Returning to border-box and origin 0 0, the two scale/translation orders produce left edges 10 and 20 with width 220. The layout left edge remains 0 and width 110.

Examples

document.body.style.margin='0';
const parent=document.createElement('div');
parent.style.cssText='width:500px;height:200px';
const box=document.createElement('div');
box.style.cssText='width:80px;height:30px;padding:10px;border:5px solid;transform-box:border-box';
parent.append(box);document.body.append(parent);
const measure=value=>{box.style.transform=value;const r=box.getBoundingClientRect();return [r.left,r.top,r.width].join(',')};
const border=measure('translateX(50%)');
box.style.transformBox='content-box';
const content=measure('translateX(50%)');
const negative=measure('translateX(-20px)');
const calc=measure('translateX(calc(50% - 5px))');
box.style.transformBox='border-box';box.style.transformOrigin='0 0';const first=measure('translateX(10px) scaleX(2)');
const second=measure('scaleX(2) translateX(10px)');
console.log('border='+border+'; content='+content+'; negative='+negative+'; calc='+calc+'; orders='+first+' / '+second+'; layout='+box.offsetLeft+','+box.offsetWidth+'; unitless='+CSS.supports('transform','translateX(20)'));

Result

border=55,0,110; content=40,0,110; negative=-20,0,110; calc=35,0,110; orders=10,0,220 / 20,0,220; layout=0,110; unitless=false

The printed triples are left, top and visible width. The order comparison explicitly restores border-box, so a content-box origin offset does not obscure the difference.

Sources