HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

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.

Example

.example {
  max-width: 500px;
}    
You can click on above box to edit the code and run again.

Output

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;

Example

.div ex1 {
  width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
} 
.div ex2{
  max-width: 500px;
  margin: auto;
  border: 3px solid #73AD21;
} 
You can click on above box to edit the code and run again.

Output

This <div> element has width: 500px;
This <div> element has max-width: 500px;

Tip: Drag the browser window to smaller than 500px wide, to see the difference between the two divs!