CSS: Width and Max-Width

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?


Solution 1:

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.

Solution 2:

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.

Solution 3:

In your first example

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

you are telling the browser to give a width of 98% of the screen, but not bigger than 1140px.

In your second example,

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

you are telling the browser to give a width of 1140px but not larger than 98% of the browser.

But, in the second instance, your screen size would need to be smaller than 1140px for the max-width value to kick in.

Also note that max-width is buggy in many older versions of IE.

Read more here: http://reference.sitepoint.com/css/max-width