I'm having a problem centering an element that has the attribute position set to absolute. Does anyone know why the images are not centered?
body { text-align: center; } #slideshowWrapper { margin-top: 50px; text-align: center; } ul#slideshow { list-style: none; position: relative; margin: auto; } ul#slideshow li { position: absolute; } ul#slideshow li img { border: 1px solid #ccc; padding: 4px; height: 450px; } <body> <div id="slideshowWrapper"> <ul id="slideshow"> <li><img src="https://source.unsplash.com/random/300*300?technology" alt="Dummy 1" /></li> <li><img src="https://source.unsplash.com/random/301*301?technology" alt="Dummy 2" /></li> </ul> </div> </body> Answer: Use the CSS margin , left & right property You can align any absolutely or fixed positioned <div> element horizontally center using the CSS margin property in combination with the left and right position property.
If you have set a width you may use:
position: absolute; margin-left: auto; margin-right: auto; left: 0; right: 0; text-align: center;
Without knowing the width/height of the positioned1 element, it is still possible to align it as follows:
EXAMPLE HERE
.child { position: absolute; top: 50%; /* position the top edge of the element at the middle of the parent */ left: 50%; /* position the left edge of the element at the middle of the parent */ transform: translate(-50%, -50%); /* This is a shorthand of translateX(-50%) and translateY(-50%) */ } It's worth noting that CSS Transform is supported in IE9 and above. (Vendor prefixes omitted for brevity)
Adding top/left of 50% moves the top/left margin edge of the element to the middle of the parent, and translate() function with the (negative) value of -50% moves the element by the half of its size. Hence the element will be positioned at the middle.
This is because a percentage value on top/left properties is relative to the height/width of the parent element (which is creating a containing block).
While a percentage value on translate() transform function is relative to width/height of the element itself (Actually it refers to the size of bounding box).
For unidirectional alignment, go with translateX(-50%) or translateY(-50%) instead.
1. An element with a position other than static. I.e. relative, absolute, fixed values.
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