Pavel Komarov
Pavel Komarov

Reputation: 1246

Need image to responsively fill responive square area

Here is my jsfiddle code.

<div class="gallery-thumbnail">
    <a href="google.com">
        <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/13Vend%C3%A9miaire.jpg/1024px-13Vend%C3%A9miaire.jpg" />
    </a>
</div>

.gallery-thumbnail {
    display: flex;
    max-width: 400px;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    background: silver;
}
.gallery-thumbnail a { /* This magic makes a square, because the padding % is of the element's width. */
    height: 0;
    padding-bottom: 100%;
}
.gallery-thumbnail img {
  position: relative;
  object-fit: cover;
  width: 100%;
  background-color: green;
}

https://jsfiddle.net/hgw7s9qf/

I spent a while searching around how to make an element square for all screen sizes, and then some more time trying to set a not-perfectly-square image inside that area. I am finding I can't have everything at once.

How can I get that image to fit-fill the square responsively, the way one would expect object-fit: cover to work, yet still maintain the area as a dynamically-resizing square?

Important: I need this to be responsive, so the square shrinks as the window does, and the image inside should too.

Upvotes: 2

Views: 101

Answers (3)

To make an image properly square you need to specify same height and width for the image. You can try like this

<div class="square">
  <div class="content">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/13Vend%C3%A9miaire.jpg/1024px-13Vend%C3%A9miaire.jpg" alt="">
  </div>
</div>

.square {
    border: 5px solid red;
    text-align: center;
    width: 50vw;
    height: 50vw;
  }

.content {
}
.content img{
  height: 50vw;
  width: 50vw;
}

Working Fiddle

Square Image

Upvotes: 0

Pavel Komarov
Pavel Komarov

Reputation: 1246

I found a way.

I am not really sure why it works, exactly. Maybe one of you brilliant people can help with that.

.gallery-thumbnail {
    position: relative;
    width: 100%;
    padding-bottom: 100%;
}
.gallery-thumbnail img {
    position:absolute;
    object-fit: cover;
    width:100%;
    height:100%;
}

https://jsfiddle.net/7f13rnvu/

Upvotes: 1

PhilB
PhilB

Reputation: 184

I'm not entirely sure what your end goal is but with the same markup, I got this to work:

.gallery-thumbnail {
    max-width: 400px;
    background: red;
}
.gallery-thumbnail img {
  display: block;
  object-fit: cover;
  width: 100%;
  height: 400px;
}

After reading this, I think that the image needs both width and height for object-fit to work its magic as it's fitting within the image sizing.

Hope that helps.

Upvotes: 0

Related Questions