简体   繁体   中英

image with a preferred width, min-width and max-width

I have an image which I'd like to scale according to the following rules with increasing importance:

  • normally has a width of 38% (of the parent/screen);
  • not become smaller than 300px;
  • never become larger than 100% (of the parent/screen) (only an issue if the parent/screen is smaller than 300px;

That is to say: the image takes only a percentage of the available space but should not become too small on smaller screens. However, for very small screens (mobile devices), the image may never exceed the full width of the available space, even if this would mean it shrinks below the minimum width.

I thought I could do this with the following css:

img {
    width: 38%;
    min-width: 300px;
    max-width: 100%;
}

thinking that the max-width would take preceedence over the min-width because it appears later. But it is not working... The image appears as the required percentage and is not shrinking below 300px. However, on a small screen (<300px), the image extends out of the screen (scrollbars appear).

Reading the docs, min-width overrides max-width , so I should have seen this coming...

One obvious solution would be to add a media query:

@media screen and (max-width: 300px) {
    img {
        min-width: 0;
        width: 100%;
    }
}

However, I would like to be able to override the width specifics (ie the 38% or the 300px values) from within the html (tag style).

Several questions on SO touch on the topic of sizing, but I could not find one about my exact case. Anyone here with a solution/suggestion?

Some side requirements:

  • should work in major browsers, html5/css3
  • no javascript (if it turns out that it's not possible with css only, I will create a js solution, but I prefer no js for this)
  • no media queries (see above)
  • I am in control of the html, so nesting inside additional elements is fine if needed

If min-width overrides max-width , then the solution is to not set min-width to a value that can become greater than the window width.
In other words, swap around the values for width and min-width . Then you won't need media queries or JavaScript.

 img { width:300px; min-width:38%; max-width:100%; } 
 <p><img src="https://placehold.it/999x333"/></p> <p><img src="https://placehold.it/999x333" style="width:400px"/></p> 

In this example, both images are never smaller than 38% and never larger than 100% of the window, and the first image prefers 300px while the second one prefers 400px.

(Note that the images themselves say they are "999×333"; you should ignore that.)

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