Reputation: 27
Is there any difference between declaring both width
and max-width
and declaring only one?
As I have understood, using only the max-width
property causes all of an element's content to be fit dynamically when the viewport is resized.
Upvotes: 1
Views: 257
Reputation: 450
Using max-width
, as the name implies, means that, when a container contains more content than it can fit, its width won't exceed the specified max-width
.
max-width
is specifically used to prevent a container's width from increasing when it contains more content than it can fit—instead, when max-width
is specified, the content will overflow out of the container.
Upvotes: 0
Reputation: 481
Consider the following pen, feel free to resize the window to see what happens:https://codepen.io/harrison-rood/pen/KKzPQMW
The first example is an image with an explicit width of 800px.
The second is an image with a max-width of 800px, but a width of 100%.
See how one is responsive and the other is not? In the first example, we're telling the image it needs to be exactly 800px. In the second example, we're saying that the image should be a fluid 100%, but not any bigger than 800px, no matter what.
You can also use this idea in reverse. The third example has an image with a width of auto
(as big as possible) but a max width of 100%, meaning that it will be as big as its container, but not overflow out of it.
The fourth example shows what would happen without max width. See how the image stretches way past its container because it is much larger?
Hope this clears things up! If it does, be sure to leave an upvote!
Upvotes: 2
Reputation: 13
This is because screen resolutions can be different sizes. Lets say you have an element with a width of 15%
, if you increase your window width, 15% becomes larger in pixels. You can set a max-width from preventing it from going over a certain width in pixels.
Upvotes: 0