When styling an element, you have the option to set both a width
and a max-width
. The element will adhere to the specified width, but will shrink if the max-width is smaller.
You can find more information about this behavior on the MDN website.
This approach ensures that the width property does not exceed the value set for max-width.
img {
background-color: grey;
border: 1px solid blue;
width: 400px; /* Ideal width */
max-width: 80%; /* Max width */
}
<img src="http://placehold.it/400x400">
It's worth noting, as mentioned in another response, that you can set width
as a percentage and max-width
as pixels. Ultimately, the result is the same: the image's width will be determined by the smaller of the two values.
In my opinion, setting the width in pixels aligns better with the semantic meaning. You're defining the image to be a specific number of pixels wide (in relation to the image itself), while using a percentage as a constraint for smaller screens. However, feel free to approach it the other way around too - no judgment here!