Home > Mobile >  Why does max-width and width display a completely different result?
Why does max-width and width display a completely different result?

Time:05-28

I am working on my CSS skills and by watching Kevin Powell's video "How to use CSS object-fit to control your images", I couldn't understand why the use of either max-width or width would completely alter the result. Here's the HTML:

<div > 
 
  <img  src="//unsplash.it/500" alt="">

</div>

And here is the first CSS code (pay attention to tard .card__image 's width)

.card{
background: lightgreen;
width: 350px;
padding: 3rem;
}

.card__image{
width: 100%;
height: 150px;
}

On the second version of the CSS code, we switch .card__image's width to "max-width". Now I don't understand why when we use "width", the image is stretched out and takes the entire width of the parent element it's inside of, but when we use "max-width",it's as if it no longer focuses on the parent element but on the image itself. It proportionally fixes the image's dimensions so the image would appear in full/no stretch, inside the parent element.

In result, with "width", the image is stretched out and takes the entire parent element's space. With "max-width", the image is not stretched out and simply takes whichever amount of space it needs to.

How come ?

CodePudding user response:

The difference between width: 100% and max-width:100% is that: First, width define the width of the specific element while max-width define the maximum size the element is allow to have link

  • Related