CSS force image resize and keep aspect ratio

前端 未结 23 894
野趣味
野趣味 2020-11-22 10:04

I am working with images, and I ran across a problem with aspect ratios.

\"\"

23条回答
  •  -上瘾入骨i
    2020-11-22 10:36

    https://jsfiddle.net/sot2qgj6/3/

    Here is the answer if you want to put image with fixed percentage of width, but not fixed pixel of width.

    And this will be useful when dealing with different size of screen.

    The tricks are

    1. Using padding-top to set the height from width.
    2. Using position: absolute to put image in the padding space.
    3. Using max-height and max-width to make sure the image will not over the parent element.
    4. using display:block and margin: auto to center the image.

    I've also comment most of the tricks inside the fiddle.


    I also find some other ways to make this happen. There will be no real image in html, so I personly perfer the top answer when I need "img" element in html.

    simple css by using background http://jsfiddle.net/4660s79h/2/

    background-image with word on top http://jsfiddle.net/4660s79h/1/

    the concept to use position absolute is from here http://www.w3schools.com/howto/howto_css_aspect_ratio.asp

提交回复
热议问题