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

When to use Width and Max-Width?

I need help wrapping my head around width and max-width.

So width is just saying "this is the width of an element / image / etc"

Max-width states "this is how wide the element can ever become"

This is useful so that if you have an image or element that has a dynamic size (in other words it can be shrunk or enlarged depending on the browser window size), the element or image can shrink smaller, but not exceed a certain width for larger windows.

1 Answer

Using width sets block-level elements to a fixed width. Using max-width allows the element to expand to the amount of content inside, but can be no wider than the specified max width.

The nice thing is that when you use max-width, it can help makes the layout more flexible and responsive to different screen sizes. Say you have a DIV with a width of 800px full of text. On a desktop it looks great, but on a mobile device you have to scroll horizontally because the width is fixed to 800px. If you had used max-width instead, the element could contract in width to match the device width, perhaps 320px and potentially eliminate horizontal scrolling.