Here’s a quick and easy way to create an unlimited width, scrollable horizontal container using nothing but some simple CSS. The trick here is as simple as using display: inline-block; on the child elements inside of the parent container, in combination with the white-space: nowrap; property.

Let’s say this is our markup:

<div class="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
    <div>6</div>
    <div>7</div>
    <div>8</div>
    <div>9</div>
    <div>10</div>
    <div>11</div>
    <div>12</div>
</div>

With a little bit of CSS love, we can implement this quickly and easily, like so. Please note the use of the font-size: 0; trick I’m using here to remove the whitespace between the inline-block children. By setting font-size: initial; on the child elements, we reset font sizes to be able to cascade them as needed again. This avoids nasty margin-left: -4px; hacks and such.

.container {
    box-sizing: border-box; // if you want container to conform to viewport
    width: 100%;
    min-height: 150px;
    font-size: 0; // removes 4px space between inline-block items
    white-space: nowrap;
    border: 4px solid red;
    overflow-x: auto;
    
}
.container > div {
    display: inline-block;
    width: 25%;
    height: 150px;
    background: #ccc;
    font-size: initial; // resets font-size
    line-height: 150px;
    text-align: center; 
}
.container > div:nth-of-type(even) {
    background: #ddd;
}

That’s it! You can see a demo over at JSFiddle or check it out below:

Leave a Reply

Your email address will not be published. Required fields are marked *

Continue Reading