Search code examples
cssslidercenteringindicator

How do I center my indicator items in a slider when the number images (items) is variable?


I have a slider that has the focus image centered but I'm having trouble centering the indicator items (dots) because each slider has a different number of images. Here is my HTML for the slider and the indicator:

<div class="main">
<section id="slider" >
<div class="container-fluid">      
    <div class = 'responsiveHeight'>
        <div class = 'inner'>
            <div class = 'iosSlider'>
                <div class = 'slider'>
                <img class="item selected" src="/park-terrace/00-park-terrace.jpg" alt="Park Terrace"/>
                <img class="item " src="/park-terrace/01-park-terrace.jpg" alt="Park Terrace"/>
                <img class="item " src="/park-terrace/02-park-terrace.jpg" alt="Park Terrace"/>
                </div>
            </div>
        </div>
        <div class="prevButton"></div>
        <div class="nextButton"></div>
    </div>
</div> <!-- /.container -->
<div class = 'indicators'>
    <div class = 'item selected'></div>
    <div class = 'item'></div>
    <div class = 'item'></div>
</div>
</section>

Here is my CSS:

    .main {height:432px;}
#slider {
        position:absolute;
        top:100px;
        left:0px; 
        width:100%;
        color:#666;
        z-index:1;
    }
.responsiveHeight {
        height: 0;
        padding: 0 0 80% 0; 
        position: relative;
        overflow:hidden;
        }
.responsiveHeight > .inner {
        position: absolute;
        width: 100%;
        height: 100%;
        }
.iosSlider {
        width: 100%;
        height: 100%;
        }
.iosSlider .slider {
        width: 100%;
        height: 100%;
        }
.iosSlider .slider img {
        height: 100%;
        padding-right:2px;
        }


.indicators {
    position: relative;
    top: 10px;
    left: 150px;
    width: 400px;
    height: 10px;
    margin: 0 auto;
    z-index: 10;
}

.indicators .item {
    float: left;
    width: 12px;
    height: 12px;
    margin: 0 5px 0 0;
    border-radius: 10px;
    background-color:#666;
}

An example of the problem is below:

small number of images large number of images

I'm hoping there is a way to adjust my css rather than use javascript. I'm open to any suggestions and I appreciate your help.


Solution

  • If i'm understanding you correctly, we can isolate this down to just the 'indicators'. You can use flexbox to pop these in the center:

    .indicators {
      width: 100%;
      display: flex;
      justify-content: center;
      padding: 40px 0;
    }
    
    .indicators .item {
        width: 12px;
        height: 12px;
        margin: 0 5px 0 0;
        border-radius: 10px;
        background-color:#666;
    }
    <div class='indicators'>
        <div class='item selected'></div>
        <div class='item'></div>
        <div class='item'></div>
    </div>