Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: Width and Max-Width

Tags:

Why does:

width: 98%;
max-width: 1140px;

do the same as

width: 1140px;
max-width: 98%;

The first one makes sense in that I'm saying the width is 98% but don't go larger than 1140px wide.

The second one however would say the page is 1140px wide but then WOULD go as large as the page at 98% right? So e.g past 1140px... but apparently not, as it does the same as the first.

Can someone explain why?

like image 253
Cameron Avatar asked Jun 23 '11 15:06

Cameron


People also ask

What is difference between width and max width in CSS?

First, width define the width of specific element while max-width define the maximum size the element is allow to have.

Does Max Width override width CSS?

max-width overrides width , but min-width overrides max-width .

Can you use width and max width together?

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 is Max Width 100 in CSS?

"width" is a standard width measurement for defining the exact width of an element. Defining "width:100%" means that the width is 100%. Defining "max-width:100%" means that the width can be anywhere between 0% and 100% but no more then 100%.


2 Answers

From my understanding of the properties:

if width > max-width use max-width
if max-width > width use width

Therefore, using your example, this must mean that 1140px is strictly less than 98% at the screen resolution you are viewing at.

Shrink your browser screen and you will get different results.

It's somewhat unrelated, but I've found max-width (and the corresponding property max-height) to be a problem with images in Internet Explorer, and found this to be helpful in coaxing it to use the correct values:

img {
    max-width: 150px;
    max-height: 120px;
    width: auto !important;
    height: auto !important;
}

Without the last two properties, most standard-compliant browsers correctly maintain aspect ratio, but Internet Explorer will not unless you do that.

Edit: It looks like I've said basically the same answer as everyone else.

like image 121
Anthony Sottile Avatar answered Sep 22 '22 04:09

Anthony Sottile


If you set a fixed width and a max-width, this means the following:

If the width goes above max-width, keep it at max-width. If the width is below max-width, keep it on width.

It will never go over the max-width, that doesn't mean it can't stay under, the max keyword obviously indicates a limit and not a rule.

like image 25
Kokos Avatar answered Sep 20 '22 04:09

Kokos