Search code examples
htmlcssimagecentering

Image cuts only from right when scaling


Im trying to put this big image centered. Every time I make the image bigger the window cuts ONLY his right side. It doesn't look centered that way. Also I don't need it in position ABSOLUTE, since I dont want a scroll sideways.

CSS

.container {
padding-top:70px;
overflow:hidden;
}

.slideimg{
display:block;
margin:auto;
height:800px;

}

HTML

<div class="container">

<img class="slideimg" src="images/back.jpg" >

</div>

Solution

  • Use this combination of settings for the image to center it horizontally also if it's wider than the viewport:

    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    

    Copy the heigth: 800px; to the container DIV and define position: relative; for the container. Here' the full example:

    .container {
      position: relative;
      height: 800px;
      padding-top: 70px;
      overflow: hidden;
    }
    
    .slideimg {
      display: block;
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
      height: 800px;
      width: auto;
    }
    <div class="container">
    
      <img class="slideimg" src="http://placehold.it/1500x1000/fa0">
    
    </div>