CSS width 100% OR max-width in pixels

CssWidth

Css Problem Overview


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

Css Solutions


Solution 1 - Css

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;
}

Solution 2 - Css

If it's block level element it should be 100% by default so no need to declare the width, then max-width: 512px; would curtail it

calc() is not supported very well at all, but in this case I wouldn't think you would need it

Solution 3 - Css

div{ max-width: 512px; }

should suffice.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMikko OhtamaaView Question on Stackoverflow
Solution 1 - CssBoltClockView Answer on Stackoverflow
Solution 2 - CssclairesuzyView Answer on Stackoverflow
Solution 3 - CssIan WoodView Answer on Stackoverflow