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

前端 未结 14 2525
粉色の甜心
粉色の甜心 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:44

    One of the answers includes the background-size: contain css statement which I like a lot because it is straightforward statement of what you want to do and the browser just does it.

    Unfortunately sooner or later you are going to need to apply a shadow which unfortunately will not play well with background image solutions.

    So let's say that you have a container which is responsive but it has well defined boundaries for min and max width and height.

    .photo {
      max-width: 150px;
      min-width: 75px;
      max-height: 150px;
      min-height: 75px;
    }
    

    And the container has an img which must be aware of the pixels of the height of the container in order to avoid getting a very high image which overflows or is cropped.

    The img should also define a max-width of 100% in order first to allow smaller widths to be rendered and secondly to be percentage based which makes it parametric.

    .photo > img {
      max-width: 100%;
      max-height: 150px;
      -webkit-box-shadow: 0 0 13px 3px rgba(0,0,0,1);
      -moz-box-shadow:    0 0 13px 3px rgba(0,0,0,1);
      box-shadow:         0 0 13px 3px rgba(0,0,0,1);
    }
    

    Note that it has a nice shadow ;)

    Enjoy a live example at this fiddle: http://jsfiddle.net/pligor/gx8qthqL/2/

提交回复
热议问题