Extend a div width based on its children width
Asked Answered
C

3

12

Here is my little problem (the value are just here for the example):

Lets say I have a window with a width around 500px. Inside my document, I have an outer div with no specified width, but the following css:

.outer{
  white-space:nowrap;
  background:blue;
}

Inside this div are 3 other div that have the following properties:

.t1{
  display:inline-block;
  width:400px;
}

(notice the width of 400px. That's where the problem is, the line is wider than the window, and the outer div does not extend. The HTML looks like that:

<div class="outer">
    <div class="t1">1</div>
    <div class="t1">2</div>
    <div class="t1">3</div>
</div>

What I'm trying to achieve is to have the 3 inner div with a blue background, without setting it for the t1 class. What this example will produce is a blue background limited to the width of the window.

See full example here : http://jsfiddle.net/sjCTR/ (you'll have to adapt the bottom left corner if your screen is to large)

I'm wondering if somehow that could be achieved thru css/html only, without setting the outer div width/the inner div background?

Chios answered 8/4, 2012 at 23:8 Comment(2)
Not sure I understand your problem. Are you trying to force the width of each .t1 to always be 400px or always 33% or something else?Fickle
No, The number i put in here are there only for the example. The problem is more complex, but the idea is that the width of the outer div wouldn't grow to fit its children width.Chios
A
30

Add float: left or display: inline-block to .outer.

Ahithophel answered 8/4, 2012 at 23:28 Comment(2)
Thank you very much. Both are working. Could you explain how is that magic possible (I mean why adding that to outer make it expand)?Chios
You saved me from hours of headacheTweeze
B
0

add overflow: hidden; width:100%; to outer

Barbados answered 8/4, 2012 at 23:45 Comment(0)
S
0

To explain @thirtydot answer,

Div is block-level element:

A block-level element always starts on a new line and takes up the full width available (stretches out to the left and right as far as it can).

So in default the width of the parent is 100%. If you change this to inline-block or inline you get the effect you want.

An inline element does not start on a new line and only takes up as much width as necessary.

Stepparent answered 19/5, 2023 at 21:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.