Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

CSS

Julian Ptak
Julian Ptak
30,920 Points

CSS Question: What is the difference between Width and Max-Width?

Hey Treehousians,

I'm practicing my work in CSS and I'm having a hard time understanding the difference between width and max-width.

What I'm trying to do is set a responsive site so that it floats three paragraphs at the same level on the widest setting, then it would clear one underneath it and stretch it across on the middle level, and finally at the smallest screen size, it would display them all in a column.

Strangely, the smallest screen size is working fine. Perhaps that's the simplest? But the mid screen size and large screen size are showing some odd symptoms. One such symptom is that the third paragraph is staying stubbornly below the other two as if it were cleared to the left. There seems to be plenty of space though on the same line. What I can't figure out is whether or not I should be using "width" or "max-width" for this and also whether this is a "width/max-width" problem at all or if this is a "float/clear" problem. Any ideas? Any debugging suggestions? Here's my responsive code just so you can see what I'm on about:

@media screen and (min-width: 480px) {

  /**********************************
  TWO COLUMN LAYOUT
  ***********************************/

  #primary {
    max-width: 50%;
    float: left;
        background: red;
  }

  #secondary {
    max-width: 30%;
    float: left;
    background: #2CC94D;
    margin-bottom: 1.2%;
    padding-bottom: 1.2%
  }

  #extra{
      clear: left;
      max-width: 100%;  
  }

 footer {
    clear: both; 
 }

  /**********************************
  PAGE: ABOUT
  ***********************************/

  .profile-photo {
    float: left;
    margin: 0 5% 80px 0;
  }


}

@media screen and (min-width: 780px) {

  /**********************************
  HEADER
  ***********************************/

  #primary, #secondary, #extra{
        margin: 0, 0, 0, 2.5%;
        padding: 0, 0, 0, 2.5%;  
  }

  #primary {
    max-width: 35%;
    font-size: 1.2em;
    float: left;
    background: blue;

  }

  #secondary {
    width: 30%;
    background: yellow;
  }

  #extra {
      max-width: 15%;
  }

  nav {
    background: none;
    float: right;
    clear:right;
    font-size: 1.125em;
    margin-right: 5%;
    text-align: right;
    width: 45%;
  }

  #logo {
    float: left;
    margin-left: 5%;
    text-align: left;
    width: 45%;
  }

  h1 {
    font-size: 2.5em;
  }

  h2 {
    font-size: 0.825em;
    margin-bottom: 20px;
  }

  header {
    border-bottom: 5px solid #599a68;
    margin-bottom: 60px;
  }


}

3 Answers

Erik McClintock
Erik McClintock
45,783 Points

Julian,

You can think of the difference between width and max-width as follows: assigning an element a width property gives it its definitive, end-all-be-all width. You are stating that "element X's width is Y", plain and simple. Assigning an element the max-width property, however, is stating that "element X's width CANNOT be MORE than Y, but CAN be LESS than Y". Thus, if you assign an element just a max-width property, it will simply take up as much space as necessary to wrap around the element(s) contained within it. If both properties are present on a given element, and width is greater than max-width, max-width will be applied. If, however, max-width is greater than width, width will be applied.

Max-width is helpful if you want to plan for your site to be viewed on overly-large screens, such as televisions or just regular ol' gigantic desktop monitors that some people may have. If you think your design will expand poorly to match those larger screen sizes, you can set max-width to make it so your design will remain true to exactly what you want, as your elements will NOT grow past the value you assign to their max-widths.

NOTE - the same (though converse) goes for min-width.

Something to keep an eye on when designing responsive websites with multi-column layouts is the total percentage that your divs or sections add up to in a given row. There are some browser inconsistencies in regards to what percentage they'll start knocking blocks down to the next line on, but if you make sure to not exceed 100% for the sum of all the elements you want in a given row (and sometimes it's even safest to go a tiny bit beneath 100% to prepare for those browser quirks), you should be good to go. You have to remember that the borders and margins applied to any of your elements will contribute to this total, as well.

An example of a simple, responsive, three-column layout using the width value and percentages:

<!doctype html>
<html lang="en-US">
    <head>
        <title>Page Title</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <section class="container">
            <div id="col1">First column</div>
            <div id="col2">Second column</div>
            <div id="col3">Third column</div>
            <div class="clearfix"></div>
        </section>
    </body>
</html>
.container {
    width: 66%;
    margin: 0 auto;
}

.clearfix {
    clear: both;
}

#col1 {
    height: 200px;
    background: tomato;
    width: 60%;
    float: left;
}

#col2 {
    height: 200px;
    background: steelblue;
    width: 30%;
    float: left;
}

#col3 {
    height: 200px;
    background: limegreen;
    width: 10%;
    float: left;
}

Notice there are no margins or borders added to any of the elements, so the only numbers to calculate are their individual widths, which add up to 100% (60 + 30 + 10).

As you resize your browser, you'll notice the three divs shrinking to fit the new size of their containing parent element (the section), due to the use of percentages for their widths. To make the layout change you described once you hit the 780px break point, you would simply add the following media query to your CSS:

@media screen and (max-width: 780px) {
        #col1 {
        width: 65%;
    }

    #col2 {
        width: 35%;
    }

    #col3 {
        width: 100%;
    }
}

Here, I've changed the totals of #col1 and #col2 to add up to 100%, and I've given the column we want to slip below to a new line a total of 100% width, which will force it to be 100% of the width of its containing parent element, thus exceeding the 100% of the row it used to be in, which will push it down now to the next available space beneath the other elements.

And then, once you hit the 480px mark, you would want to have the following in your CSS:

@media screen and (max-width: 480px) {
        #col1 {
        width: 100%;
    }

    #col2 {
        width: 100%;
    }

    #col3 {
        width: 100%;
    }
}

This applies the same technique, where now each element is set to take up 100% of the available width of its containing parent element, which will force each of them into their own new rows.

Hopefully this helps to clarify some of the points you were wondering about!

Erik

Erik McClintock
Erik McClintock
45,783 Points

A note regarding your code: You currently have the media queries in your sample code set to watch for the min-width of the viewport; you want to watch the max-width. Change those properties and try your code again.

Remember that the min-width means "if the viewport is this size or BIGGER", and max-width means "if the viewport is this size or SMALLER". You can only go UP from the minimum, and only go DOWN from the maximum. Thus, if you set:

@media screen and (min-width: 480px) {
    /*code goes here*/
}

...your code throughout the rest of your stylesheet, including other media queries, will not run, because you're stating that "if the viewport is at LEAST 480px or BIGGER, apply the code here". So unless your viewport is SMALLER than 480px, your other styles will be ignored.

Max-width is what you want to set to achieve the desired results. If you set:

@media screen and (max-width: 480px) {
    /*code goes here*/
}

...your code is saying that "when the viewport is 480px or SMALLER, run this code". Thus, once your viewport reaches 481px, your media query handling that new size will apply, or your standard styles will apply if that was the only break point you had set.

Again, hope this helps to clarify!


Erik
Julian Ptak
Julian Ptak
30,920 Points

Erik,

Thanks so much for your response! It was incredibly helpful! In case anyone else comes to this page with the same question, I've created a fiddle of your code. I hope you don't mind.

Here it is: http://jsfiddle.net/f7qW9/10/

Thanks again, Erik. I'm very VERY new to CSS and I'm trying to pick it up quickly. This explanation was perfect. Thank you!

God bless, Julian

Erik McClintock
Erik McClintock
45,783 Points

Julian,

You're very welcome! Also, great idea about consolidating it and putting it into a jsfiddle for others. +1 for that!

Here's another little bit of code that you can add to the HTML for the jsfiddle that may help people understand it better as they resize the viewport:

<p>Window Size: <span id="size"></span>px</p>
<script>
    window.onresize = function() {
        document.getElementById("size".innerHTML = window.innerWidth;
    };
</script>

Add that directly above the closing body tag, and it will add a visual indicator that will display the current viewport size in pixels as the viewport changes. That way, you can watch the pixel value and see exactly when and how your break points are working!

Erik

Julian Ptak
Julian Ptak
30,920 Points

Updated it! Thanks, Erik!

Erik McClintock
Erik McClintock
45,783 Points

Julian,

Looks like I left out the closing parenthesis on the call to getElementById, so the code is not working! If you pop the closing mark in, though, it'll work like a charm.

...
<script>
...
document.getElementById("size").innerHTML = window.innerWidth;
...
</script>

Erik

Julian Ptak
Julian Ptak
30,920 Points

Yep! That worked! I'll update the link. Thanks again!