css: max-width or max-size

121 views Asked by At

On my website I have images that have a width of 720 pixels. I want images to be either 95% of the width of the page (max-width: 95%), or 720px if the page width is too large. So, on larger screens, I don't want to blow them up. Is there a way to achieve this in CSS?

2

There are 2 answers

1
GolezTrol On

You can specify a width and a max-width. The element will respect the width, or shrink if max-width is smaller.

This behavior is described on the MDN.

It prevents the used value of the width property from becoming larger than the value specified 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">

Note as indicated in the other answer, you could set width to a percentage and max-width to pixels. The end result is the same: the calculated width of the image becomes the smallest of the two.

To me, specifying the width in pixels makes more sense semantically. After all, you want to have an image of so many pixels wide (related to the image itself), and want to have a constraint on the percentage for smaller screens. But if you write it the other way around, I won't hold it against you. ;-)

5
Stewartside On

GolezTrol has it nearly right but just has the max-width and width values the wrong way round.

Below is the correct elements set as you require.

img {
  width: 95%; /* Ideal width */
  max-width: 720px; /* Max width */
  }
<img src="http://placehold.it/800x800">