How to properly scale and position images inside of containers using CSS

Issue

I am trying to create a meme page and have containers filled with images. Some images are wide and some are super long, I want to display them in a way such that the container is of set size (for example 50% screen width, height can be auto) and the image inside is cropped and centered. I think it is best to illustrate it with some photos.

This is what I want:

enter image description here

And this is what I am getting:

enter image description here

The key is getting these white stripes on the top and bottom if the image is too wide and left and right if the image is too long.

Here is my CSS code:

.homePage {
  width: 100%;
  min-height: calc(100vh - 80px);
  height: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-top: 20px;
}

.homePage .post {
  width: 50%;
  background-color: rgb(250, 250, 250);
  box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
  margin: 20px;
  padding: 20px;
  border-radius: 15px;
}

.post .postHeader {
  display: flex;
  justify-content: center;
  width: 100%;
}

.postHeader .title {
  flex: 50%;
}
.postHeader .deletePost {
  flex: 50%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.deletePost button {
  border: none;
  background: none;
  font-size: 30px;
  cursor: pointer;
}

.post .postImgContainer {
  word-wrap: break-word;
  height: auto;
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content:center;
  overflow: hidden;
  overflow-y: auto;
}

Whenever I change flex-direction from column to row in .postImgContainer it seems to be working, but only for one case of images, the other are getting stretched out.

Thank you for your help!

Solution

Using flex, you can position the image in the desired position depending on the maximum width and height stipulated in the image container. I hope you can see it clearly with this example, let me know if you really need something else.

Try this:

body {
  min-height: 100vh;
}

.container {
  width: 100%;
  background: blue;
}

.meme {
  width: 50%;
  margin: 15px auto;
  height: 600px;
  background: green;
  display: flex;
  justify-content: center;
  align-items: center;
}

.meme-img {
  max-height: 100%;
  max-width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
  <div class="container">
    <div class="meme">
      <img src="https://cdn.pixabay.com/photo/2022/05/30/14/24/stairs-7231312_960_720.jpg" class="meme-img">
    </div>
    <div class="meme">
      <img src="https://cdn.pixabay.com/photo/2015/10/29/14/38/web-1012467_960_720.jpg" class="meme-img">
    </div>
  </div>
</body>
</html>

Answered By – Ivanquez

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.