htmlcssclearfix

Building horizontal slider - divs floating vertically


I am trying to build simple horizontal image slider with overflow:hidden and floating divs. Hovewer, I am not able to float them horizontally - they always appear in vertical order. I tried many examples from the web, hovewer I still don't know where I am wrong.

HTML:

<div id="slidingWindow">
    <div class="slidingSection clearfix">Something something</div>
    <div class="slidingSection clearfix">Again something</div>
</div>

CSS:

#slidingWindow {
overflow:hidden;
width: 470px;
height: 500px;
background-color: red;
}

.slidingSection {
margin: 5px;
background-color: green;
width: 470px;
height: 400px;
float: left;
}

.clearfix:after { 
content: "."; 
visibility: hidden; 
display: block; 
height: 0; 
clear: both;
}

This JSFiddle contains simplest example of my problem: http://jsfiddle.net/v4udd47t/


Solution

  • If your support is IE10+ and are not concerned with Opera Mini, then you can use display: flex. That way you don't need any extra markup or even floats and clearfix.

    Along with using flex you will also have to set a min-width on the slides that is equal to the container minus any margins and padding. In regards to margins and padding, the container will also have to accommodate any that are applied to the slides (I noticed you have a 5px margin on them).

    HTML:

    <div id="slidingWindow">
        <div class="slidingSection clearfix">Something something</div>
        <div class="slidingSection clearfix">Again something</div>
    </div>
    

    CSS:

    #slidingWindow {
        overflow:hidden;
        width: 480px; /* width of slide + left and right margins */
        height: 500px;
        background-color: red;
        display: -ms-flex;
        display: -webkit-flex;
        display: flex;
    }
    
    .slidingSection {
        margin: 5px;
        background-color: green;
        width: 470px;
        min-width: 470px; /* required */
        height: 400px;
    }
    

    Below is a fork of your fiddle with the size reduced and having an animation on hover to show it is working properly:

    #slidingWindow {
    	overflow:hidden;
        width: 260px;
        height: 300px;
        background-color: red;
        display: -ms-flex;
        display: -webkit-flex;
        display: flex;
    }
    
    .slidingSection {
        margin: 5px;
        background-color: green;
    	width: 250px;
        min-width: 250px;
    	height: 200px;
        -webkit-transition: -webkit-transform 750ms;
    	transition: transform 750ms;
    }
    
    #slidingWindow:hover > .slidingSection {
        -webkit-transform: -webkit-translate3d(-260px, 0, 0);
        transform: translate3d(-260px, 0, 0);
        -webkit-transition: -webkit-transform 750ms;
        transition: transform 750ms;
    }
    <div id="slidingWindow">
        <div class="slidingSection">Something something</div>
        <div class="slidingSection">Again something</div>
    </div>