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?
Just use display: flex
and justify-content: center
on the parent element
body {
text-align: center;
}
#slideshowWrapper {
margin-top: 50px;
text-align: center;
}
ul#slideshow {
list-style: none;
position: relative;
margin: auto;
display: flex;
justify-content: center;
}
ul#slideshow li {
position: absolute;
}
ul#slideshow li img {
border: 1px solid #ccc;
padding: 4px;
height: 100px;
}
<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>
<!-- Images from Unsplash-->
You can find this solution in JSFIDDLE
html, body, ul, li, img {
box-sizing: border-box;
margin: 0px;
padding: 0px;
}
#slideshowWrapper {
width: 25rem;
height: auto;
position: relative;
margin-top: 50px;
border: 3px solid black;
}
ul {
list-style: none;
border: 3px solid blue;
}
li {
/* center horizontal */
position: relative;
left: 0;
top: 50%;
width: 100%;
text-align: center;
font-size: 18px;
/* center horizontal */
border: 3px solid red;
}
img {
border: 1px solid #ccc;
padding: 4px;
//width: 200px;
height: 100px;
}
<body>
<div id="slideshowWrapper">
<ul id="slideshow">
<li><img src="http://via.placeholder.com/350x150" alt="Dummy 1" /></li>
<li><img src="http://via.placeholder.com/140x100" alt="Dummy 2" /></li>
<li><img src="http://via.placeholder.com/200x100" alt="Dummy 3" /></li>
</ul>
</div>
</body>
Use margin-left: x%;
where x is the half of the width of the element.
A simple CSS trick, just add:
width: 100%;
text-align: center;
This works on both images and text.
Using
left: calc(50% - Wpx/2);
where W is the width of the element works for me.
#parent
{
position : relative;
height: 0;
overflow: hidden;
padding-bottom: 56.25% /* images with aspect ratio: 16:9 */
}
img
{
height: auto!important;
width: auto!important;
min-height: 100%;
min-width: 100%;
position: absolute;
display: block;
/* */
top: -9999px;
bottom: -9999px;
left: -9999px;
right: -9999px;
margin: auto;
}
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:
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
More details about the first example can be found here:
Maintain the aspect ratio of a div with CSS