- Home
- CSS
- Layout
- Transform centering
Vertically and horizontally centers a child element within its parent element using CSS transforms.
- Set the
position
of the parent torelative
and that of the child toabsolute
to place it in relation to its parent. - Use
left: 50%
andtop: 50%
to offset the child 50% from the left and top edge of the containing block. - Use
transform: translate[-50%, -50%]
to negate its position, so that it is vertically and horizontally centered. 💬 Note
The fixed height
and width
of the parent element is for demonstration purposes only.
.parent { border: 1px solid
9C27B0;
height: 250px; position: relative; width: 250px; } .child { left: 50%; position: absolute; top: 50%; transform: translate[-50%, -50%]; text-align: center; }
More like this
Collection · 5 snippets
CSS Centering
A collection of techniques for centering HTML elements in any situation using CSS.CSS · December 30, 2020
Flexbox centering
Horizontally and vertically centers a child element within a parent element using flexbox.CSS · December 30, 2020
Grid centering
Horizontally and vertically centers a child element within a parent element using .parent { border: 1px solid
9C27B0;
height: 250px; position: relative; width: 250px; } .child { left: 50%; position: absolute; top: 50%; transform: translate[-50%, -50%]; text-align: center; } 0.CSS · December 30, 2020
Display table centering
Vertically and horizontally centers a child element within its parent element, using .parent { border: 1px solid
9C27B0;
height: 250px; position: relative; width: 250px; } .child { left: 50%; position: absolute; top: 50%; transform: translate[-50%, -50%]; text-align: center; } 1.
What does transform translate 50 50 %] mean?
For example, if you have a div element with a width and height of 200px, applying transform: translate[-50%, -50%]; to it will move the div 50% to the left and 50% up, effectively centering it within its parent container. Here is an example of how it can be used: css.
What does top 50% mean in CSS?
The CSS property top works exactly as left . It pushes the div from that direction. When you write top:50% , the div will be pushed down 50% from the top. You want it to be centered vertically, so you need to counter this by pulling it back up.
How to translate left CSS?
The translate transform moves an element right, left, up, or down. A positive X value moves the element to the right and a negative X value moves the element to the left. A positive Y value moves the element downwards and a negative Y value moves the element upwards.
What is top 0 and left 0 in CSS?
Setting top: 0; left: 0; bottom: 0; right: 0; gives the browser a new bounding box for the block. At this point the block will fill all available space in its offset parent, which is the body or position: relative; container.