htmlcssimagecentralized

How to centralise images with an absolute position?


I have three images in a <div>. I want the images to overlay each other (for a slideshow using opacity) and remain central on my website.

To make the images overlay I set their position to absolute (position: absolute;). However, this conflicts with my method of centralising my images. To make my images central, I give images the following properties: margin: 0 auto; display: block; This doesn't work when the images' positions are set to absolute. What other methods can I use to make my images overlay and/or centralise images.

<div>
<img  id="SlideShow1" src="Images\image1.jpg" width="512" height="512">
<img  id="SlideShow2" src="Images\image2.png" width="512" height="512">
<img  id="SlideShow3" src="Images\image3.jpg" width="512" height="512">
</div>


img {
position: absolute;
   margin: 0 auto;
    display: block;
}

Solution

  • Another option is by using CSS3 transform:

    img{
      display:block;
      position:absolute;
      left:50%;
      transform:translate(-50%,0);
    }
    

    Add vendor prefixes as needed.

    This has also been mentioned in an answer under the question Center an image with CSS (horizontal and vertical).