user2076675
user2076675

Reputation:

How do I style a div with inner floats to expand horizontally to allow all inner floating divs to fit?

Basically, I have a content box with some floating items:

html

<div class="contentBox">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>

css

.contentBox {
    overflow-x:scroll;
}
.item {
    float:left;
}

I want the box to expand in width to let as many items as I add to it to fit, floating left (which means the elements get pushed to the right). But instead it only goes as wide as the page before the items drop down because of having no room. I want it to continue on outside of the page.

How do I do this?

I'm thinking I'll need to use some JavaScript, but I'd rather a pure CSS solution if it's possible.

Upvotes: 1

Views: 52

Answers (3)

Dynamic Remo
Dynamic Remo

Reputation: 531

Here you GO :) Only add this on you button click.

$('button').click(function() {
  var item = $('.item').length + 1;
   $('.contentBox').append('<div class="item">' + item + '</div>');

   var w = window.innerWidth;
   var l = $(".contentBox div").length + 1;
   $(".contentBox div").each(function(){
        $(this).css("width", w/l);
   });
});

Check this JSFiddle Link http://jsfiddle.net/DynamicRemo/8krcm0x6/

Upvotes: 0

Andrew Dunai
Andrew Dunai

Reputation: 3129

You can set display: table-cell for .item.

Here's an example: http://jsfiddle.net/andunai/fq201q8b/

Upvotes: 1

dfsq
dfsq

Reputation: 193271

You can use white-space: nowrap on parent container with inline-block child elements:

.contentBox {
    overflow-x: scroll;
    white-space: nowrap;
}
.item {
    display: inline-block;
}

Demo: http://jsfiddle.net/vo8202uy/

$('button').click(function() {
    $('.contentBox').append('<div class="item">' + ($('.item').length+1) + '</div>');
});
.contentBox {
    overflow-x:scroll;
    white-space: nowrap;
}
.item {
    width: 50px;
    background: coral;
    margin-right: 5px;
    display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="contentBox">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
</div>
<button>Add more</button>

Upvotes: 1

Related Questions