Andrew Nielsen
Andrew Nielsen

Reputation: 113

How to make inner div adjust width to its child elements

I have a container div with width, height and overflow-x auto. I want to be able to scroll the elements inside horizontally. inside i have an inner container that hold all the elements.

If i give the inner div a fixed width, in this case 3000 pixels, and it works but i want it to adjust its width dynamically. How can i accomplish this?

Here is my fiddle.

https://jsfiddle.net/95yb8k1f/

<div class="outer" style="width:100%; height:500px;overflow-x:auto;">
    <div class="inner" style="height:100%; width:3000px;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
       <div class="item" style="height:100%; width:300px; float:left;">
   </div>
</div>

Upvotes: 1

Views: 2113

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122027

You need to use white-space:nowrap; on .inner and display: inline-block; on .item

div.outer {
  width:100%;
  height:400px;
  overflow-x:scroll;
  overflow-y: hidden;
}

div.inner {
  position:relative;
  height:100%;
  white-space:nowrap; 
}

div.item {
  width:300px;
  height:100%;
  display: inline-block;
}

div.item:nth-child(2n+1){
  background:blue;
}

div.item:nth-child(2n+2){
  background:green;
}
<div class="outer">
  <div class="inner">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</div>

Upvotes: 2

Related Questions