Search code examples
javascripthtmlcsscarousel

Why do my carousel images disappear (zero carousel height) when carousel slider is placed inside a div?


I am using this "Image Slider with Dots (pure JS)" codepen which works very well on the page by itself, but whenever I place it inside a div for example an "outer shell" the images in the slider disappear, but the dots stay visible. I am going to be using it on a page that has a content wrapper so that's how I ran into this issue of the carousel having zero height once it is placed inside another div.

Here is the HTML of the slider with my custom class "outer-shell" around it, which makes the slider have zero height:

<div class="outer-shell">
    <!-- this slider can be used multiple times on the same page -->
<!-- don't change class names because slider will not work -->
<div class="slider">
    <div class="imgs">
      <!-- you can add divs with class img here and they will be 
           automatically added to slider -->
      <!-- style="left: 0;" in case JS is disabled -->
      <div class="img" style="left: 0;"> 
        <span>Image 1</span>
      </div>
      <div class="img">
        <span>Image 2</span>
      </div>
      <div class="img">
        <span>Image 3</span>
      </div>
      <div class="img">
        <span>Image 4</span>
      </div>
    </div>
    <div class="dots"></div>
  </div>
</div>

There's quite a bit of CSS and JS along with the HTML, I thought it would be easier to have it linked rather than pasting it here. "Image Slider with Dots (pure JS)"

I have spent a good amount of time using Chrome Developer Tools looking at the individual pieces of the slider (trying different overflow properties), and I think it comes down to the images have an absolute position, because when I deselect the css property the first image would show. I am not sure if the outer div is messing up the positioning of the page?


Solution

  • i think your .dots class have position: absolute; that is why it is shown inside your div without needed a height property and when you add height to outer-shell you can see images too.

    <div class="outer-shell">
     <div class="slider">
      <div class="imgs">
        <!-- you can add divs with class img here and they will be 
             automatically added to slider -->
        <!-- style="left: 0;" in case JS is disabled -->
        <div class="img" style="left: 0;"> 
          <span>Image 1</span>
        </div>
        <div class="img">
          <span>Image 2</span>
        </div>
        <div class="img">
          <span>Image 3</span>
        </div>
        <div class="img">
          <span>Image 4</span>
        </div>
      </div>
      <div class="dots"></div>
     </div>
    </div>
    
    .outer-shell{
      height: 100%;
      max-width:80%;
      margin:0 auto;
    }