user1845791
user1845791

Reputation: 1003

DIV Horizontal Scroll

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!

Upvotes: 8

Views: 26232

Answers (3)

Zeddy
Zeddy

Reputation: 2089

In your root DIV element you could always specify that overflow is scrollable:

<div id="container" style="overflow: scroll;">
  <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>

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

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/

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

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

Upvotes: 23

Related Questions