I would like to create a css class so a div can be placed in the center of its parent. The code I am using is:
.centered { position: absolute; margin: auto; bottom: 0px; left: 0px; top: 0px; right: 0px; }
It works if the parent is larger than the child element, or has the same size: https://jsfiddle.net/cy8dn1km/
But if the child is larger, then its center is not positioned at the center of its parent. Instead their left borders will be at the same place, and the child element will be extended only to right:
https://jsfiddle.net/797L7nce/
Something is wrong with the horizontal centering.
How is it possible to fix it using CSS only (without using CSS 2D/3D transformations), without adding new container elements?
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
To just center the text inside an element, use text-align: center; This text is centered.
Simply give the child element a property of margin: with a value of 0 auto; . This will automatically size the margin on the left and right sides of the div evenly to one another.
In this case, we set the child element's width to be 100% of the viewport width by using a percentage viewport unit (vw), then, we move it to the left side (by the distance of the viewport's half, minus 50% of the width of the parent element) with the left property.
Add left: 50%; transform: translate(-50%, 0);
and remove right: 0px;
.centered { position: absolute; margin: auto; display: block; bottom: 0px; top: 0px; left: 50%; transform: translate(-50%, 0); }
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With