Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Div inside overflow="auto" to auto size its width to its contents

Tags:

html

css

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 .items.

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 .items end up stacking vertically. I give the .container a fixed height, but the .items 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 .items to stack horizontally.

My question:

What CSS do I apply to .container to make the .items stack horizontally?

like image 645
Jimmery Avatar asked Jan 12 '23 02:01

Jimmery


2 Answers

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.

like image 77
Hashem Qolami Avatar answered Jan 22 '23 21:01

Hashem Qolami


Add display:inline-block to your .item
The default display for DIVs is block and this cause a vertical stack, But display:inline-block makes all DIVs to arrange them self in a horizontal line

Difference of varient display options:

Inline elements:

  • Respect left & right margins and padding, but not top & bottom
  • Cannot have a width and height set
  • Allow other elements to sit to their left and right.

Block elements:

  • Respect all of those
  • Force a line break after the block element

Inline-block elements:

  • Allow other elements to sit to their left and right
  • Respect top & bottom margins and padding
  • Respect height and width.

Derived from Oldskool answer
More info in W3schools

like image 38
frogatto Avatar answered Jan 22 '23 20:01

frogatto