Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS width 100% OR max-width in pixels

Tags:

css

width

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

like image 827
Mikko Ohtamaa Avatar asked Apr 15 '11 10:04

Mikko Ohtamaa


People also ask

Should you use 100% width?

Should it Ever Be Used? In many cases, applying width: 100% to a block level element is either unnecessary or will bring undesirable results. If you're using padding on the inner element and you use box-sizing: border-box , then you'll be safe.

Should I use max-width or width?

This is a simple way to put it: if the element would render wider than the max-width says it should be, then the max-width property wins over the width property. But if it would render less than the max-width says, then the width property wins. In mathematical terms: if width > max-width; let the browser use max-width.

What does width 100% do in CSS?

width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent.


2 Answers

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; } 
like image 184
BoltClock Avatar answered Sep 20 '22 09:09

BoltClock


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

like image 20
clairesuzy Avatar answered Sep 20 '22 09:09

clairesuzy