Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Set min-width and max-width of an element using CSS
The CSS min-width and max-width properties are used to set the minimum and maximum width constraints for an element. These properties are particularly useful for creating responsive designs that adapt to different screen sizes.
Syntax
selector {
min-width: value;
max-width: value;
}
Possible Values
| Value | Description |
|---|---|
length |
Defines width in px, em, rem, etc. |
% |
Defines width as a percentage of the parent container |
auto |
Default value, no constraint applied |
none |
No maximum width limit (for max-width only) |
Example
The following example demonstrates how min-width and max-width work together. Resize your browser window to see the effect −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
max-width: 400px;
min-width: 200px;
background-color: #ff6b6b;
padding: 20px;
margin: 20px auto;
border-radius: 8px;
color: white;
font-family: Arial, sans-serif;
}
.info {
background-color: #4ecdc4;
padding: 10px;
margin-top: 10px;
border-radius: 5px;
font-size: 14px;
}
</style>
</head>
<body>
<p>Resize the browser window to see how the div below responds to width changes:</p>
<div class="container">
This container has a minimum width of 200px and maximum width of 400px.
When you resize the browser window, this element will never shrink below 200px
or expand beyond 400px, regardless of the available space.
<div class="info">
Current behavior: The width adapts between 200px and 400px based on available space.
</div>
</div>
</body>
</html>
A responsive red container with white text appears on the page. When you resize the browser window, the container width changes but stays between 200px (minimum) and 400px (maximum). A teal information box is nested inside showing the current behavior.
Key Points
-
min-widthprevents an element from becoming smaller than the specified value -
max-widthprevents an element from becoming larger than the specified value - These properties override the
widthproperty when conflicts occur - Useful for responsive design and maintaining readability across different screen sizes
Conclusion
The min-width and max-width properties provide essential control over element sizing in responsive designs. They ensure your content remains readable and well-proportioned across different viewport sizes.
Advertisements
