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

前端 未结 4 1390
北恋
北恋 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:

    <div class="apple_container"><div class="apple_icon"></div></div>
    

    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.

    0 讨论(0)
  • 2020-12-11 19:27

    I figured out how to do this without js, though you need to use a transparent image.

    Set up a html structure like:

    <div class="rect_container"><img class="rect_image" src="rect_image.png"/>
     <div class="rect">Your favorite content here</div>
    </div>
    

    Use a AxB transparent png for rect_image where AxB is the aspect ratio.

    Meanwhile set up a stylesheet like:

    .rect_container {width: 50%; position: relative;}
    .rect_image {width: 100%; display: block;}
    .rect {width: 100%; height: 100%; position: absolute; left: 0px; top: 0px;}
    

    The important thing here is taking advantage of the fact that images maintain their aspect ratio when resized in one direction. Meanwhile, we need a useable div, so we make the image display as block, wrap it in a div, and put an absolutely positioned div inside that. I distilled this code from something more complicated I actually tested. Works like a charm.

    0 讨论(0)
  • 2020-12-11 19:37

    jQuery sounds pretty easy. Set the 50% width in the CSS, and then the following:

    function onResize() {
        var el = $('#element');
        el.height(el.width());
    }
    $(window).resize(onResize);
    $(document).ready(onResize);
    
    0 讨论(0)
  • 2020-12-11 19:38

    Here you go: Detecting a browser resize using JQuery.

    0 讨论(0)
提交回复
热议问题