How to create horizontal scrolling content in a div using CSS
Although horizontally scrolling content is usually frowned upon, in some circumstances, it is necessary and even desirable - for instance, take a look at Apple’s horizontal list of products on it’s site. On their site, they have made use of a combination of CSS to create the horizontally scrolling content, and JavaScript to skin the scrollbar to fit in with the website design.
To create the horizontally scrolling div, firstly, we need the following HTML:
<div id=”horizontal”>
<img src=”example1.jpg” alt=”" />
<img src=”example2.jpg” alt=”" />
<img src=”example3.jpg” alt=”" />
</div>
Now, we need some CSS:
#horizontal {width: 500px;
height: 200px;
overflow: auto;
white-space: nowrap;}
These 4 lines are all that is necessary to style the div - although you can obviously add more to customize the look as necessary. The width and height declare the permanent size of the div, while overflow: auto tells the browser to add a scrollbar if the content exceeds the size of the div and white-space: nowrap tells the browser to wrap the content entirely, even if it exceeds the size of the div element.
And that’s it - as long as your images are larger than the div, then they will be wrapped horizontally and a scrollbar will be added for navigation. For customizing the look of the scrollbar, you will need to use JavaScript - jsScrollbar is one of many pre-prepared examples of scripts that give scrollbars a custom look.
Note: one problem that can prevent the above code from working is if you use line breaks (<br />) in between the images.
Tags: CSS overflow, custom scrollbar, horizontally scrolling, HTML div



Leave a Reply