Shrink-to-fit

Introduction: This page illustrates one aspect of CSS 2.1 'shrink-to-fit' and proposes an additional CSS 3 option - see 'Important' below.

CSS demonstration: This code is used for the following live demonstration which enables you to see the effect of changing the width of your browser window:

<div style='overflow: hidden; width: 100%; background: maroon'>
<div style='float: left; margin: 5px; background: yellow'>
<div style='float: left; margin: 5px; width: 300px; height: 30px; background: red'></div>
<div style='float: left; margin: 5px; width: 300px; height: 30px; background: green'></div>
<div style='float: left; margin: 5px; width: 300px; height: 30px; background: blue'></div>
</div></div>

Description: The yellow enclosing box shrinks to fit the red, green and blue boxes provided they are on one line. CSS 2.1 says: "Calculation of the shrink-to-fit width is similar to calculating the width of a table cell using the automatic table layout algorithm." This prohibits further reduction of the width of the yellow box beyond the point at which the blue box is forced onto the next line. Firefox 3.5.2, iCab 4.5 and Safari 4.0.3 conform to this but Camino 1.6.9 (updated August 2009), Firefox 2.0.0.20 (updated July 2008) and IE 5.2.3 (updated May 2003) continue to shrink the yellow box over multiple lines.

Images: The following two half-size images show how the above code is displayed by Firefox 2 and Firefox 3 at the point where the blue box has just been forced onto the next line.

shrink-to-fit

JavaScript demonstration: The following live demonstration uses this page-specific JavaScript to calculate yellow width from maroon width after load, resize and unload. This should cause all browsers to shrink the yellow box like Firefox 2 so that you can change window width and see the result:

function w() { x=document.getElementById('m').clientWidth-10; document.getElementById('y').style.width=(x-x%310)+'px' }
window.onload=w; window.onresize=w; window.onunload=w // onunload fixes a WebKit back-button issue

Conclusion: I contend that the more intuitive Firefox 2 effect is very useful and that providing it as an additional CSS 3 option would relieve web designers from the futility of trying to create it with CSS. As far as I am aware CSS 2 compliant browsers can only achieve this effect with script.

Important: The more people that request this additional option the more likely it is to find its way into future CSS specifications. You can help by sending a supporting email, with a link to this page, to at least one of: flexible box editor, basic box editor and CSS public mailing list.

html | css | 4413 hits since September 2009 | updated 2011-09-26 | webmaster