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

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

    Simple elegant working solution:

    img {
      width: 600px;  /*width of parent container*/
      height: 350px; /*height of parent container*/
      object-fit: contain;
      position: relative;
      top: 50%;
      transform: translateY(-50%);
    }
    

提交回复
热议问题