1

I am trying to center an image but when I specify padding, the image element is not centered.

Sandbox link

HTML

<div class="imageParent">
            <figure id='img-div'>
                <img class='image card'
                    src='https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg'
                    alt='Cat sleeping' />
                <figcaption id='img-caption'>
                    <p class='centeredText'> Cat sleeping </p>
                </figcaption>
            </figure>
        </div>

CSS

.image {
        background: white;
        max-width: 100%;
        height: auto;
        display: block;
        margin: 0 auto;
        padding: 2em 2em 4em 2em;
      }

      @media (max-width: 500px) {
        .image {
          padding: 1em 1em 2em 1em;
        }
      }
yuvalm2
  • 866
  • 2
  • 10
  • 27
noName94
  • 3,783
  • 1
  • 16
  • 32
  • Ah, there's much more in that exact question - "why". :) While the provided solution certainly is a good answer (it solves the issue), there're many interesting things running under the carpet here. Have you noticed that dropping that external `
    ` element - or just resetting its margins with `figure { margin: 0; }` - makes the margins for that image the same?
    – raina77ow Sep 20 '20 at 07:54

1 Answers1

2

Use box-sizing: border-box; for your image. This will help you in making the padding inside the container div. In your scenario the padding will be considered apart from the 100% width of the image. This makes the image to move out of the container due to the extra padding.

Docs.

border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.

.image {
  background: white;
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
  padding: 2em 2em 4em 2em;
  box-sizing: border-box;
}

@media (max-width: 500px) {
  .image {
    padding: 1em 1em 2em 1em;
    box-sizing: border-box;
  }
}
<div class="imageParent">
  <figure id="img-div">
    <img
      class="image card"
      src="https://img.webmd.com/dtmcms/live/webmd/consumer_assets/site_images/article_thumbnails/other/cat_relaxing_on_patio_other/1800x1200_cat_relaxing_on_patio_other.jpg"
      alt="Cat sleeping"
    />
    <figcaption id="img-caption">
      <p class="centeredText">Cat sleeping</p>
    </figcaption>
  </figure>
</div>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49