CSS: 100% width or height while keeping aspect ratio?

前端 未结 14 2529
粉色の甜心
粉色の甜心 2020-11-28 21:05

Currently, with STYLE, I can use width: 100% and auto on the height (or vice versa), but I still can\'t constrain the image into a specific positio

14条回答
  •  無奈伤痛
    2020-11-28 21:42

    Some years later, looking for the same requirement, I found a CSS option using background-size.

    It is supposed to work in modern browsers (IE9+).

    And the style:

    #container
    {
      width:  100px; /*or 70%, or what you want*/
      height: 200px; /*or 70%, or what you want*/
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
    }
    

    The reference: http://www.w3schools.com/cssref/css3_pr_background-size.asp

    And the demo: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size

提交回复
热议问题