Home > OS >  How to make image fit in div?
How to make image fit in div?

Time:06-08

I am trying to create a simple card, where image should cover/fit the full width of the container div.
My desired style would be something similar like in the image below.
enter image description here

I tried to apply object-fit:cover with 100% width but didn't help.

Here is how it looks like now

enter image description here

Here is related code and sandbox link
html/jsx

import React from "react";
import styles from "./Card.module.css";

function App() {
  return (
    <div className={styles.cardWrapper}>
      <img
        src="https://i.ebayimg.com/00/s/MTAyNFg1NzY=/z/qWYAAOSwm1Vcc6F4/$_72.JPG"
        alt="description"
      />
      <h3 style={{ fontSize: "15px" }}>title</h3>
      <div className={styles.description}>description</div>
    </div>
  );
}

export default App;

and css

.cardWrapper {
  width: 165px;
  height: 192px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 25%);
  text-align: center;
  margin: 0 auto;
  align-items: center;
}

.description {
  font-size: 12px;
  color: #808080;
  margin-top: 20px;
  font-weight: 400;
}

.cardWrapper img {
  height: 100%;
  width: 100%;
  object-fit: contain;
  width: auto;
  height: auto;
}

Any help will be appreciated

CodePudding user response:

Simply remove the width: auto and height: auto from your .cardWrapper img:

.cardWrapper {
  width: 165px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  box-shadow: 0 1px 2px 0 rgb(0 0 0 / 25%);
  text-align: center;
  margin: 0 auto;
  align-items: center;
  padding-bottom: 15px;
}

.description {
  font-size: 12px;
  color: #808080;
  margin-top: 20px;
  font-weight: 400;
}

.cardWrapper img {
  height: 100%;
  width: 100%;
}
<div >
  <img
    src="https://i.ebayimg.com/00/s/MTAyNFg1NzY=/z/qWYAAOSwm1Vcc6F4/$_72.JPG"
    alt="description"
  />
  <h3>title</h3>
  <div >description</div>
</div>

You were overwriting your already working 100% rules, so just leave them in, and remove anything else. You dont need the object-fit either.

As stated by @louielyl in the comments: remove the absolute height on the .cardWrapper as well, otherwise the description has no room left in the wrapper and falls out.

CodePudding user response:

The reason why your width:100% and height:100% didn't work is because your latter css width: auto; height: auto; overwrite them.

Try this and you will see your image grows as expected:

.cardWrapper img {
  height: 100%;
  width: 100%;
  object-fit: contain;
}

It happens because it is CSS's behavior to override with the latter styling that has the same property, for details, you could take a look at Specificity.

  • Related