skip to Main Content

there are different images that i want to display inside a div box, whatever the image size, Div box size should be the same.

I couldn’t fit the image, when the image is larger, it goes out of the div box. that affects the Ui of my website that I am trying to create.

2

Answers


  1. You need object-fit.

    div {
      width: 100px;
      height: 100px;
      border: 3px solid red;
      margin-bottom: 30px;
    }
    
    img {
      opacity: 0.8;
    }
    
    .d2 img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    <p>source image larger than div so it overflows</p>
    <div class="d1">
      <img src="http://picsum.photos/id/146/180/120">
    </div>
    
    <p>source image is scaled until its shorter dimension fits the div, then the other dimension is cropped</p>
    <div class="d2">
      <img src="http://picsum.photos/id/146/180/120">
    </div>
    Login or Signup to reply.
  2. See the below code as an example and you need to make changes accordingly in your code.
    Here I am having a main div as image-container. I am applying CSS to div and image inside the div.

       <div class="image-container">
          <img src="path_to_your_image.jpg" alt="Image">
        </div>
    
    
        .image-container {
          width: 300px; /* Set your desired width */
          height: 200px; /* Set your desired height */
          overflow: hidden; /* Ensure that the image doesn't overflow the container */
          background-color: #ccc; /* Optional: set a background color for the container */
        }
        
        .image-container img {
          width: 100%; /* Ensure the image fills the container horizontally */
          height: auto; /* Maintain aspect ratio */
          display: block; /* Remove any potential whitespace below the image */
        }
    

    Hope it helps and see how it goes.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search