skip to Main Content

I have a layout problem where I want to center images horizontally that is bigger than the container they are in. the container size is 800px and the images are 1200px.
when I use regular max-width and margin:0 auto it results in something like this. how can I make the images centered horizontally in this layout and keep the image size to 1200px
enter image description here

But I want it to be something like this:
enter image description here

3

Answers


  1. width: 100% should work perfectly. It will be easier to answer if you share your code.

    Login or Signup to reply.
  2. I suggest you just change the HTML with <div> separator, it will make sense for the image width will follow its parents instead of the paragraph’s parent.


    Before:

    .center {
      margin: auto;
      width: 300px;
      height: 50px;
      border: 1px solid black;
    }
    <div class="center">
      <p>div in window center</p>
      <img src="https://picsum.photos/1200/800" />
      <p>div in window center</p>
      <img src="https://picsum.photos/1200/800" />
    </div>

    After (run this snippet only on full page version):

    .center {
      margin: auto;
      width: 300px;
      height: 50px;
      border: 1px solid black;
    }
    <div class="center">
      <p>div in window center</p>
    </div>
    
    <div>
      <img src="https://picsum.photos/1200/800" />
    </div>
    
    <div class="center">
      <p>div in window center</p>
    </div>
    
    <div>
      <img src="https://picsum.photos/1200/800" />
    </div>
    Login or Signup to reply.
  3. Apply display: block; and position:relative;to your image to make it possible to move it, thenleft: 50%;(which moves its left side to the center of the parent container) andtransform: translateY(-50%);`, which moves it to the left by 50% of its own width.

    All this together will center it horizontally the way you asked for.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search