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>
Your images are not centered because your list items are not centered; only their text is centered. You can achieve the positioning you want by either centering the entire list or centering the images within the list.
A revised version of your code can be found at the bottom. In my revision I center both the list and the images within it.
The truth is you cannot center an element that has a position set to absolute.
But this behavior can be imitated!
Note: These instructions will work with any DOM block element, not just img.
Surround your image with a div or other tag (in your case a li).
Note: The names given to these elements are not special.
Alter your css or scss to give the div absolute positioning and your image centered.
And there you have it! Your img should be centered!
Your code:
Try this out:
I hope this was helpful. Good luck!
probably the shortest
You can try this way :
What seems to be happening is there are two solutions; centered using margins and centered using position. Both work fine, but if you want to absolute position an element relative to this centered element, you need to use the absolute position method, because the absolute position of the second element defaults to the first parent that is positioned. Like so:
Until I'd read this posting, using the margin:0 auto technique, to build a menu to the left of my content I had to build a same-width column to the right to balance it out. Not pretty. Thanks!
This worked for me: