Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand the parent div of floated elements to fit their total width?

I am trying to put together a page that will have a horizontally scrolling pane on it - here is an example of the layout I am looking to get: enter image description here The content is dynamically added and has varying dimensions. .

Here's some HTML:

<div class="container">
    <div class="inner">
        <div></div>
        <div></div>
        <div></div>
    </div>
</div>

Base CSS:

.container {
    width: 100%;
    height: 100%;
}

.container .inner {
    position: relative 
}

.container .inner > div {
    float: left;
}

Currently the only way I can get it working is by setting an explicit width for .inner. Otherwise, closest I've come is this answer, but it's still pretty far off my desired effect. Is it possible to achieve what I'm looking for with HTML/CSS alone or will I have to resort to javascript?

like image 615
styke Avatar asked Jan 04 '14 17:01

styke


1 Answers

Is this what you expected? http://jsfiddle.net/GE5Hf/4/

enter image description here

Just use white-space: nowrap together with the inline-block and vertical-align: top. You don't need your .inner div to achieve the desired effect - just use one container with overflow-x: auto:

<div class="container">
        <div id="i1"></div>
        <div id="i2"></div>
        <div id="i3"></div>
</div>

CSS

.container {
    width: 100%;
    height: 100%;
    overflow-x: auto;
    white-space: nowrap; 
}

.container > div {
    display:inline-block;
    vertical-align: top;
}

Note: it is better to use overflow-x: auto than scroll just in case the scrollbar is not needed.

EDIT: We were speculating whether you actually need that .inner div. If you need it, you can just add it back with no special style required: http://jsfiddle.net/GE5Hf/5/

EDIT 2: To have the .inner div the width as its children, simply give it display:inline-block: http://jsfiddle.net/GE5Hf/8/

EDIT 3: Tried what you suggested in your last deleted comment, i.e. remove the fixed width of the child. This was really tricky, I had to wrap each child element to special div with display: table-cell and the inner div gets dislay: table-row: http://jsfiddle.net/GE5Hf/12/

like image 91
Tomas Avatar answered Oct 10 '22 00:10

Tomas