Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DIV Horizontal Scroll

Tags:

html

css

I have several HTML elements inside a div with a fix width. The sum of the width of the inner elements is greater than the width of the container. How can I make the inner elements appear inline (and showing a horizontal scroll) instead of breaking after reaching the parent's width?

I could add a wrapper and assign it a min-width, but I want something that will change its size if the contents change.

<div id="container">
    <div class="contents" id="one"></div>
    <div class="contents" id="two"></div>
    <div class="contents" id="three"></div>
    <div class="contents" id="four"></div>
</div>

#container {
    width: 100px;
    background-color: #CCC;
    overflow: auto;
    height: 100px;
}

.contents {
    width: 35px;
    height: 60px;
    float: left;
}
#one {
    background-color:#ABC;
}
#two {
    background-color:#333;
}
#three {
    background-color:#888;
}
#four {
    background-color:#AAA;
}

http://jsfiddle.net/elohr/G5YZ6/2/

Thanks!

like image 200
user1845791 Avatar asked Apr 25 '13 01:04

user1845791


People also ask

How do I horizontally scroll a div?

Set the overflow-y: hidden; and overflow-x: auto; that will automatically hide the vertical scroll bar and present only the horizontal scrollbar. The white-space: nowrap; property is used to wrap text in a single line. Here the scroll div will be horizontally scrollable.

How do I add a scroll horizontally?

Horizontal scrolling can be achieved by clicking and dragging a horizontal scroll bar, swiping sideways on a desktop trackpad or trackpad mouse, pressing left and right arrow keys, or swiping sideways with one's finger on a touchscreen.

How do you make a div scrollable?

Making a div vertically scrollable is easy by using CSS overflow property. There are different values in overflow property. For example: overflow:auto; and the axis hiding procedure like overflow-x:hidden; and overflow-y:auto;.


2 Answers

Use display:inline-block instead of float:left, and add white-space:nowrap; to the container. If needed, add white-space:normal to the content elements. Demo

like image 146
Niet the Dark Absol Avatar answered Oct 22 '22 12:10

Niet the Dark Absol


Try this:

  1. Replace float: left with display: inline-block;
  2. Use white-space: nowrap; to the container.

CSS:

#container {
    width: 100px;
    background-color: #CCC;
    overflow: auto;
    height: 100px;
    white-space: nowrap;
}

.contents {
    width: 35px;
    height: 60px;
    display: inline-block;
}

Fiddle: http://jsfiddle.net/praveenscience/G5YZ6/6/

like image 23
Praveen Kumar Purushothaman Avatar answered Oct 22 '22 13:10

Praveen Kumar Purushothaman