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="img/dummy1.JPG" alt="Dummy 1" /></li>
<li><img src="img/piano_unlicened.JPG" alt="Dummy 2" /></li>
</ul>
</div>
</body>
An absolute object inside a relative object is relative to its parent, the problem here is that you need a static width for the container
#slideshowWrapper
, and the rest of the solution is like the other users sayshttp://jsfiddle.net/ejRTU/10/
If you want to center an absolute element
If you want a container to be centered left to right, but not with top to bottom
If you want a container to be centered top to bottom, regardless of being left to right
Update as of December 15, 2015
Well I learnt this another new trick few months ago. Assuming that you have a relative parent element.
Here goes your absolute element.
With this, I think it's a better answer than my old solution. Since you don't have to specify width AND height. This one it adapts the content of the element itself.
Centering something
absolute
ly positioned is rather convoluted in CSS.Change
margin-left
to (negative) half the width of the element you are trying to center.To center a “position: absolute” element.
Sample;
Snippet;
I don't remember where I saw the centering method listed above, using negative top, right, bottom, left values. For me, this tehnique is the best, in most situations.
When I use the combination from above, the image behaves like a background-image with the following settings:
More details about the first example can be found here:
Maintain the aspect ratio of a div with CSS