CSS Layout - width and max-width
In CSS, the width and max-width properties are used to control the width of an element. These properties are particularly important for managing the layout and responsiveness of a webpage.
Width Property:
- The width property sets the width of an element to a specific value. This value can be specified in various units such as pixels (px), percentages (%), em units, etc.
- If you set a fixed width for an element, it will have that exact width regardless of the size of its container or the viewport.
Example
.example { width: 500px; }
In this example, the element with the class example will have a fixed width of 300 pixels.
Max-Width Property:
- The max-width property, on the other hand, sets the maximum width of an element. It limits the width to a specified value but allows it to be smaller if the container is smaller.
- This is particularly useful for creating responsive designs, ensuring that an element does not exceed a certain width on larger screens but can shrink on smaller screens.
In this example, the element with the class example will not exceed a maximum width of 500 pixels. If the container is smaller than 500 pixels, the element will take up the full width of the container.
Using width, max-width and margin: auto;
Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!