简体   繁体   中英

Width and max-width (css)

I was reading an article explaining the css properties width and max-width and came across this example:

img { 
width: 100%;
max-width:700px;} 

This says that the fixed width of the image, should take up the entire size of the parent element — if the width of the parent element is explicitly stated, — all hundred percent of it, yet the image should never exceed 700px. It means that the image can be less than 700px, if that suits its situation better (eg smaller window size) but it should never be more. So there are two conditions here, that the width of the image can be 100% of the parent element if it wants to but it must not never be more than 700px.

But isn't it unnecessary to add the width:100% here? Doesn't max-width:700px imply that the width will be 100% if the parent is less than 700px anyway?

First, width defines the width of a specific element while max-width define the maximum size the element is allowed to have.

Second, width:100% use the parent's width to calculate the current width value whereas max-width:100% use its own original width to calculate the maximum size. So, the image with width: 100% could be larger its original size (scaled base on its parent width). On the other hand, the image with max-width: 100% could be smaller but never be scaled larger its original size (maximum valid width = 100% x original width). That's why it's called fluid image.

Let's say you put width: 700px for an image. When you re-size your screen the image stays stably 700px. Let's say you on a mobile phone and its screen width is less then 700px the image will not fit in the screen. So it will stretch out your page and make it not mobile-friendly. At the same time, when you set max-width:700px it will re-size up to 700px but when the screen goes smaller and the images don't fit in the screen it will automatically re-size it to fit the screen.

  • As far I understand you want to get the image fit to the size of its parent container with the constraint of not exceeding the width of the image more than 700px.
  • Then I will say yes it is unnecessary to give "width: 100%;" either way default value for width will get selected ie "auto".
  • Because of this whenever your parent container will be smaller than 700px, your image will fit your container (since "width: auto;").

PS-Please refer "object-fit: contain" property of CSS, as that will also help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM