Search code examples
htmlcssimagealignmentcenter

Force an image to ALWAYS stay at the middle of a div


I'm searching ways to force an image element to stay always aligned at the middle of a div even when the div element gets too small to properly center the image. Here's an explanation of what I want to do: Question.jpg

I need the solution to be purely CSS if possible?


Solution

  • Using this centering trick should give you what you want:

    img {
      position:relative; (or absolute, it depends on your needs)
      top:50%;
      left:50%;
      transform:translate(-50%, -50%);
    }
    

    This keeps the image centered no matter the size of the container it is in. It doesn't resize the image though. Based on that pic you out it seems like you didn't want that.