How to center a "position: absolute" element
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>
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)
Explanation
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.
Centering something absolute
ly positioned is rather convoluted in CSS.
ul#slideshow li {
position: absolute;
left:50%;
margin-left:-20px;
}
Change margin-left
to (negative) half the width of the element you are trying to center.
Div vertically and horizontally aligned center
top: 0;
bottom: 0;
margin: auto;
position: absolute;
left: 0;
right: 0;
Note : Elements should have width and height to be set