Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

What exactly does max-width do on a container div?

Hi there,

I am struggling to understand what max-width achieves on a container. E.g:

.container {
  width: 80%;
  margin: 0 auto;
  max-width: 1180px;
}

I understand that the first declaration will ensure that the width of the container will be 80%. Also the second declaration ensures that the container will be centered. But why the max-width declaration? Why is this beneficial?

Thanks, James.

3 Answers

Hi James,

Assigning a max-width of 1180px with a width of 80% would mean that the container will take up 80% of its own container, not to exceed 1180px. So if it was in, for example, a container which was 2000px wide, it wouldn't be able to take up 80% of that because it would stop at 1180px - the max-width property overrides the width property.

Hope that helps!

Evan deserves the best answer.

Thanks. So its essentially going to be beneficial for centering content on extra large screen resolutions?

It ensures that your container doesn't get wider than 1180px. Let's say that your width: 80% is relative to the width of the browser window, if someone looked at your .container on a big monitor with their browser maximized, 80% of the window could be much wider than 1180px. It's helpful for containing content to the middle of your page and ensuring that things like your images don't expand to enormous sizes.

Not just for centering, but it guarantees that your layout won't be displayed too large on big screens, and you can use it for making images to respect its parent width also, for example.