Search code examples
cssresponsive-designsassmedia-queries

How to make image always have padding-top 50%


I have an center image that loads with padding-top of 50%; however, when I adjust the window vertically, the background image compresses, but the image does not stay in the center. Even I fix the height to be half of what it is, then load it (so I'm not flexing the window), the background image is proportional to the viewport, but the center image is now at the bottom of the window (where it would be the viewport height was at its maximum.

I'm using sass and currently I have:

  &--some-wrapper {
    [stuff...]
    position: relative;
    padding-top: 50%;

    @include MQ(S) {
      padding-top: 50%;
      padding-bottom: 125px;
    }
  }

But it doesn't work as expected.

How do I fix this?


Solution

  • Use Flex-box technique to center image bother vertically & horizontally. SASS Styling:

    some-wrapper{
    display: flex;
    justify-content: center; /* align horizontal */
    align-items: center; /* align vertical */
    img { height: 60px; width: 60px }
    }
    

    Or you can use CSS display table-cell technique to center image also.