Reputation: 2355
I have a floated div
(class='outer'
) of fixed height with dynamic content (class='inner'
). The dimensions of the content are not known in advance. The width of the floated div
must be flexible, but still have some maximal value:
<style>
.outer {
border: 1px solid;
height: 200px;
max-width: 400px;
overflow: auto;
float: left
}
.inner {
height: 300px;
width: 300px;
background-color: red
}
</style>
<body>
<div class='outer'>
<div class='inner'></div>
</div>
<span>Text here</span>
</body>
This generally works; however, in case of excessive content height the following happens:
.outer
assumes the width of the content, as it is below its max-width
..inner
is forced into height
of the .outer
and as a result the vertical scroll bar appears..inner
is forced into a new constrained width, as the .outer
will not resize once more to accommodate the scroll bar.The fiddle: https://jsfiddle.net/w053kLkw/
Is there a way to prevent this mechanism of overflow
and have both scroll bars appearing only when needed?
Upvotes: 1
Views: 71
Reputation: 42352
Not possible in CSS AFAIK (you need JS or you should not use floats!).
When you float
an item, it is removed from the normal block formatting context
. Floated items won't respect max-width
as it will shrink to its content- so specifying a width
to outer
would be needed.
See what happens below when I set width: 400px
also.
*{
box-sizing: border-box;
}
.outer {
border: 1px solid;
height: 200px;
max-width: 400px;
width: 400px;
overflow: auto;
float: left;
}
.inner {
height: 300px;
width: 300px;
background-color: red;
}
<body>
<div class='outer'>
<div class='inner'></div>
</div>
<div style="clear: both;"></div>
<span>Text here</span>
</body>
Explanation:
According to W3C specs, a width should always be specified to floated elements (other than replaced elements
like image which has an implicit width). Otherwise we will see unpredictable behaviour.
See the section: Do floated items need a width? in this link.
If no width is set, the results can be unpredictable. Theoretically, a floated element with an undefined width should shrink to the widest element within it. This could be a word, a sentence or even a single character - and results can vary from browser to browser.
This means outer
will take the width of the inner
- and as overflow
is not visible
the browser behaves as it sees fit.
Upvotes: 2