Use CSS (and maybe JavaScript) to make an element be square (or maintain a specific aspect ratio)

前端 未结 4 1391
北恋
北恋 2020-12-11 19:04

I have a div that I want to have the following characteristics:

  • Width = 50% of its parent element
  • Height equal to whatever it needs to be in order to
4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 19:26

    Here's a pure CSS version with no img tag:

    SCSS (include Compass to render the background-size):

    .apple_container {
      width: 50%;
    }
    .apple_icon {
      padding-bottom: 100%;
      background-image: url(/images/apple.png);
      background-repeat: no-repeat;
      @include background-size(contain);
      background-position: center center;
    }
    

    CSS generated from the above:

    .apple_container {
      width: 50%;
    }
    .apple_icon {
      padding-bottom: 100%;
      background-image: url(/images/apple.png);
      background-repeat: no-repeat;
      -webkit-background-size: contain;
      -moz-background-size: contain;
      -o-background-size: contain;
      background-size: contain;
      background-position: center center;
    }
    

    Results in a square element with a background image centered and fitted within it. This is good for responsive elements that you want to resize dependent on the user's device.

提交回复
热议问题