CSS width, max-width and min-width are styling properties that allow you to determine the dimensions of an HTML element.
Contents
Defining CSS width for elements
When you're working with CSS layouts, it is very important to be able to manipulate the dimensions of the elements a document contains. To define how far a particular element stretches horizontally, you can use the CSS width
property:
In CSS, element width can be specified in either length units (pt, px, cm, etc.) or percentages (%) that describe the width in relation to the block that contains the element.
Width is a fixed value. This means it will stay as wide as you specified and not react to resizing the window or viewing the page on different-sized screens. The element with a specified width can also overflow the parent container if it is smaller in width.
In some cases this might affect the user experience in a negative way. For example, an image might not fit into a small screen, making the website not mobile-friendly.
Adding responsiveness with CSS max width and min width
To make your element able to adapt to screens and windows of various sizes without adding a horizontal scrollbar, you need to understand the usage of two more properties: max-width
and min-width
. Both of these properties override the fixed width
.
The CSS max-width
property defines the widest possible point for a responsive element, which means it can get narrower but never wider than specified. CSS min-width
works in an exact opposite manner: it specifies the narrowest possible point. An element can get as wide as it needs to, but never smaller than defined by the value of min-width
.
In the example below, you have three similar <div> elements styled using different width CSS properties. Try resizing the window and compare the way the div width changes for each one:
div.ex1 {
width: 400px;
margin: auto;
border: 4px solid #256bdb;
}
div.ex2 {
max-width: 400px;
margin: auto;
border: 4px solid #256bdb;
}
div.ex3 {
min-width: 400px;
margin: auto;
border: 4px solid #256bdb;
}
CSS width: useful tips
- There are two experimental values for the CSS
width
property: you can includeborder-box
orcontent-box
to make the width defined in length units or percentages apply to a specified box of the element. - Always make sure to check the way your element behaves when you manipulate the text size by zooming in or out.