skip to Main Content

I am trying to create a div with two images inside that you can horizontally scroll through. Each image should be the full size of the div, and upon scrolling to the right you reveal the next image. My issue is that only the right half of the first image is displayed in the div, with the left half of the second image visible next to it. When you scroll you can see the right half of the second image. How can I make it so the entirety of the first image is visible?

.carousel {
  height: 74%;
  width: 85%;
  margin-left: 7.5%;
  margin-top: 0.5%;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: scroll;
  overflow-y: hidden;
}

.carousel img {
  width: 85vw;
  height: 74vh;
  min-width: 100%;
}
<div class="carousel">
  <img src="https://via.placeholder.com/600x400">
  <img src="https://via.placeholder.com/600x400/dddddd">
</div>

2

Answers


  1. Images don’t make great flex elements. You should build your layout, then put the content inside its containers.

    Then, flexbox isn’t really appropriate here anyway. It’s main purpose is to fit things, and that’s not really what you want. You simply want a scrolling container.

    .carousel {
      height: 74%;
      width: 85%;
      margin-left: 7.5%;
      margin-top: 0.5%;
      overflow: auto;
      white-space: nowrap;
    }
    
    .carousel>div {
      display: inline-block;
      width: 100%;
    }
    
    .carousel img {
      max-width: 100%;
    }
    <div class="carousel">
      <div>
        <img src="https://via.placeholder.com/600x200">
      </div>
    
      <div>
        <img src="https://via.placeholder.com/600x200/dddddd">
      </div>
    
      <div>
        <img src="https://via.placeholder.com/600x200/aaaaaa">
      </div>
    </div>
    Login or Signup to reply.
  2. The problem is with justify-content: center. Remove that part of the code and it should work. Your code should look like:

    .carousel {
      height: 74%;
      width: 85%;
      margin-left: 7.5%;
      margin-top: 0.5%;
      display: flex;
      align-items: center;
      overflow: scroll;
      overflow-y: hidden;
    }
    
    .carousel img {
      width: 85vw;
      height: 74vh;
      min-width: 100%;
    }
    <div class="carousel">
      <img src="https://via.placeholder.com/600x400">
      <img src="https://via.placeholder.com/600x400/dddddd">
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search