paniklas
paniklas

Reputation: 315

Images are cut when using max-width 100% and height auto

I'm new to CSS, and, as my technical expertise is not quite good, I will try to explain as simply as I can. I have an image that uses half of the screen I'm using the below CSS code after reading a couple of articles

<div class="div-block-87">
  <img src="image.jpg" alt="">
</div>
img {
  max-width: 100%;
  vertical-align: middle;
  display: inline-block;
  height: auto;
}

The problem is that image is cut like below:

While when I use inspect image shown as expected, see below:

Sorry, if my description is terrible but I do not know how else to explain.

Upvotes: 3

Views: 2223

Answers (2)

dreamLo
dreamLo

Reputation: 1860

You need the container to be a grid with 2 equal columns of 1fr each and the width and height to be 100% of the visible viewport. Then your image needs to have a max-width in order to fit nicely into its container without requiring more space than what the parent decides.

* {
  margin: 0;
  padding: 0;
}

.container {
  display: grid;
  width: 100vw;
  height: 100vh;
  grid-template-columns: 1fr 1fr;
}

.div-block-87 img {
  max-width: 100%;
}
<div class="container">
  <div class="div-block-87">
   <img src="https://images.unsplash.com/photo-1625756939748-c9c745e105cf">
  </div>
  <div class="div-block-88">other block</div>
</div>

Upvotes: 0

Yuriy Yakym
Yuriy Yakym

Reputation: 3921

You can use object-fit: cover.

If you additionally need to specify image position, use object-position: center center.

Please note, that these attributes are unavailable in older browsers.

If you need to support older browsers you can use div tag instead of img and style its background (image, position, size, fitting).

Demo

Upvotes: 2

Related Questions