CSS width 100% OR max-width in pixels

Mikko Ohtamaa picture Mikko Ohtamaa · Apr 15, 2011 · Viewed 58.1k times · Source

How one could create a CSS rule for width which

  • Uses 100% width by default

  • If 100% width exceeds certain pixel width (let's say 512 px), then the width is clamped down to this pixel width

I am not sure about width and max-width relations, or how calc() is supported or could express this. This would need to work with the latest WebKit browsers and Firefox 4. IE8 etc. support not needed

Answer

BoltClock picture BoltClock · Apr 15, 2011

That's in fact the intended use of max-width. If the computed (actual) width of an element exceeds max-width, it will be constrained to the max value instead of going beyond it. Percentage versus pixels isn't relevant.

Declare both in the same rule like this (no need for the calc() function):

#somediv {
    width: 100%;
    max-width: 512px;
}