How to set a max-width as percent AND pixels?

43,552

Solution 1

width:20%;
max-width:100px;

This sets the width to 20% but caps it at 100 px.

Solution 2

One way to accomplish this is to simply use two divs

<div class="outer">
  <div class="inner">
    This content will not exceed 100px or 20% width.
  </div>
</div>

<style>
.outer {
  max-width: 90%;
}
.inner {
  max-width: 100px;
}
</style>

Solution 3

This will NOT work with different image sizes/aspect ratios. You can define max-width and max-height separately, if you know the sizes of images. Use this method for a specific group of images, but not as a general rule.

Practical example: You have 5 photos from your phone to be placed in a page and you need some text to be in the other half of screen. You reduce the size of images to 500px wide and 300px high. You want them not to exceed half the screen and not be wider than 250px on tablet. Calculate the max height: 250*300/500=150px.

.img-class {
    max-width: 50%;
}
@media (max-width: 800px) {
    .img-class {
       max-height: 150px;
    }
}

Tested on latest Chrome, Firefox and IE.

Solution 4

I had a specific problem which required a similar solution. I needed to display all images (independent of aspect-ratio, position or extra HTML markup) at their original size, up to a set maximum width in pixels. If the screen is smaller than this fixed size, it should shrink to fit. I.e. setting a width would not satisfy the requirements.

To expand on @Kiaurutis' answer:

img {
  max-width: 400px;
}

@media (max-width: 400px) {
  img {
    max-width: 100%;
  }
}

A working example can be seen here: https://jsfiddle.net/vrehxmpx/. In this example there is an image greater than 400px (always scaled down) and an image smaller than the threshold (only scaled down when the screen is smaller than the image).

To adjust for margins, borders and other stuff you might have on the image, just increase the @media's max-width.

Solution 5

You can now use css min. But you should note that IE does not support it.

width: min(20%, 100px)

https://developer.mozilla.org/en-US/docs/Web/CSS/min()

Share:
43,552
Joe Morano
Author by

Joe Morano

Updated on July 08, 2022

Comments

  • Joe Morano
    Joe Morano almost 2 years

    How can I prevent the width of a div from expanding beyond a percent AND a pixel? In other words, the browser should calculate the pixel value of the percent, and then choose the lower of the two values.

    If I were to set them both like this: {max-width:100px;max-width:20%;} the asset pipeline would simply choose the second one and ignore the first one.