Using Max-width to Set Image Width
Last updated: September 27, 2024
Using max-width to set the width of images can make our images “more adaptive” and also improve the user experience of our website.
Have you ever encountered the following situations when setting the width of images in web pages?
- To do picture adaptation on the cell phone, the width value is set to 100%, which is fine for large-size pictures, but small-size pictures will be automatically enlarged to produce a blurring phenomenon, if you don’t set it, the picture is too large and will overflow the cell phone screen.
- To display the real size of the picture on the computer side, the width attribute is not set (default is auto), so some pictures are too big and break the page body part. But if you set the width attribute to 100%, then the picture with a small width will be enlarged automatically, making the picture blurred.
- When the width of an image is less than the width of its parent element, the actual size is displayed, both on the computer and on the cell phone.
- When the width of an image is greater than or equal to the width of its parent element, the width of the parent element is displayed, both on computers and cell phones.
Of course, some people say that the width can be set to a fixed value, but a variety of pictures on the site, if the mandatory set width (here the default height value is auto), will cause incompatibility between different devices, because the width of the size of the fixed, then in the computer, cell phone above the display is also fixed. So we should set the width value for how appropriate?
If you encounter the above problem, it can be solved by the magic max-width attribute, just set the value of its attribute to 100%, which means setting the maximum width of the element allowed to be 100%.
img {max-width: 100%;}
What it does (benefits)?
Using the max-width attribute to set the width of the image is simple, convenient, and practical, but also compatible with the device, although this is only a small detail, image optimization and enhancing the user experience is very useful.
Copyright ©: We hope that you will find it useful; reproduced with permission.