skip to Main Content

Sorry, the title must be terrible to understand, but I don’t know how to really explain it.

How can I fit my image "carouselMap" in the div "carouselItem", with an aspect ratio of 2/3, the width (of the map) being 100% of "carouselItem"’s width ?

I made a paint "drawing" to explain it.

.carouselItem {
  height: 100%;
  width: 100%;
  border: 1px solid black;
}

.carouselMap {
  aspect-ratio: 2/3;
  width: 100%;
}

Paint explaination of my problem

Thanks for your help 🙏

2

Answers


  1. Chosen as BEST ANSWER

    The solution was to create a div to contain the image, make it 100% of the width, give it an aspect ratio of 2/3, and put the image inside, center it, and give it a height of 100%

    <div class="carouselItem">
       <div class="carouselImageContainer">
          <img class="carouselMap" src="/src/images/myImage.png" />
        </div>
    </div>
    
    .carouselItem {
      height: 100%;
      width: auto;
      border: 1px solid black;
    }
    
    .carouselImageContainer {
      width: 100%;
      aspect-ratio: 2/3;
      overflow: hidden;
      display: flex;
      justify-content: center;
    }
    
    .carouselMap {
      height: 100%;
    }
    

  2. Is the map an image? If so, just style .carouselMap with object-fit: cover. This style causes an image (or any ‘replaced’ element) to be scaled to fill its specified dimensions by cropping itself in either the horizontal or vertical axis in order to retain its natural aspect ratio.

    A snippet to demonstrate:

    .carouselItem {
      width: 120px;
      aspect-ratio: 2/3;
      border: 5px solid black;
    }
    
    .carouselMap {
      display: block;
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
    
    .rawImage {
      margin-top: 1em;
      width: 240px;
      border: 5px solid black;
    }
    <div class="carouselItem">
      <img class="carouselMap" src="https://picsum.photos/id/58/500">
    </div>
    
    <img class="rawImage" src="https://picsum.photos/id/58/500">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search