Most developers know that in order for a site’s structure to be responsive and mobile-friendly, it’s better to define widths of divs and other HTML elements using percentages rather than pixels. Using percentages to define widths allows the widths of HTML elements to change while maintaining the same relation to the size of its parent container, so as the viewport gets smaller, so should all of the elements within it. This is super helpful in responsive, mobile-friendly design.
Sometimes, however, using percentages instead of pixels to define widths of HTML elements can have some less than ideal side effects. For example, let’s stay you have a div whose width is defined as 80%. If a user views this div on a phone or a laptop, a div displaying at 80% might look to be perfectly proportioned. However, if a user is viewing the same div on a desktop with a large monitor, a div with an 80% width might look enormous and its dimensions will probably exceed the size at which it was meant to be displayed in the original design.
This issue could be fixed with media queries, but why bother writing so many extra lines of code when the problem could be solved with one simple CSS property? By giving a div a max-width that’s defined in pixels, it allows for the width of the div to be 80% of its parent element while never exceeding the maximum width applied to it in pixels.
Here’s an example of how it should look:
- div{
- width: 80%;
- max-width: 1000px;
- }
Use this trick and you’ll never have to worry about elements displaying too largely on an oversized monitor.