Here is my HTML:
<div class="scrollingBox">
<div class="container">
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
<div class="item">Item</div>
</div>
</div
Here is my CSS:
.scrollingBox {
height:100px;
width:300px;
overflow:auto;
}
.item {
float:left;
height:60px;
margin:5px;
width:100px;
}
The .container
can contain any number of .item
s.
My problem at the moment is the .container
will never go wider than the .scrollingBox
, and the scrolling box ends up with a vertical scroll bar, and the .item
s end up stacking vertically. I give the .container
a fixed height, but the .item
s stack vertically beyond this fixed height.
I want the .container
to have no fixed width, so it can take any number of items. I want the scroll bar to be horizontal, and I also want the .item
s to stack horizontally.
My question:
What CSS do I apply to .container
to make the .item
s stack horizontally?
By using float
property, the elements are removed from document normal flow.
You can change their display type to inline-block
too keep them in inline flow, and use white-space: nowrap;
for the container (.scrollingBox
) to keep the inline items beside each others, as follows
Here you go:
.scrollingBox {
height:100px;
width:300px;
overflow:auto;
white-space: nowrap; /* Suppress line breaks */
}
.item {
display: inline-block; /* Display the items as inline-block */
vertical-align: top; /* Align the inline items vertically at the top */
height:60px;
width:100px;
}
WORKING DEMO.
Note: You can refer my answer to remove the white space between inline-block elements.
Add display:inline-block
to your .item
The default display
for DIV
s is block
and this cause a vertical stack, But display:inline-block
makes all DIV
s to arrange them self in a horizontal line
Difference of varient display options:
Inline elements:
Block elements:
Inline-block elements:
Derived from Oldskool answer
More info in W3schools
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With