简体   繁体   中英

How To Add % Based Image To CSS? (for fluid layout)

Okay so I want to have an image that I select through CSS to be fluid based, however, this is the problem that I run into.

This is what I think in my head I have to do, however, it doesn't work:

#image { background-image:pic.jpg; height:100%; width:100%; }

But, you can't have this tag use the "height:100%;", correct? You have to set it to a pixel width. But if I want it to be fluid.. then I can't set it to a pixel width, correct?

Is there another way to do this? Thanks.

If you mean "fluid" in the sense that I'm thinking of it (responsive design sort of 'fluid'), then setting the "max-width" to "100%" should make sure that the image never overflows past its container (or in other words, goes past 100% width).

img { max-width: 100%; }

EDIT: If your issue is making the height maintain the aspect ratio, just don't specify a height property, or if you need to override an attribute setting, set the height to auto (!important) too:

img { max-width: 100%; height: auto !important; }

If you do it this way it will be fluid:

HTML:

<img src="http://news.bbcimg.co.uk/media/images/62777000/jpg/_62777247_62777242.jpg" alt="" />

CSS:

img { width: 100%; }​ img { width: 100%; }​

http://jsfiddle.net/7hMbQ/1/

Or if you want to stretch width and height to 100% try this (but the ratio will not be correct):

http://jsfiddle.net/7hMbQ/3/

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