Scale a div to fit in window but preserve aspect ratio

前端 未结 4 1113
梦毁少年i
梦毁少年i 2020-11-28 23:31

How can I scale a div to fit inside the browser view port but preserve the aspect ratio of the div. How can I do this using CSS and/or JQuery?

Thanks!

4条回答
  •  一整个雨季
    2020-11-29 00:13

    You don't need javascript for this. You can use pure CSS.

    A padding-top percentage is interpreted relative to the containing block width. Combine it with position: absolute on a child element, and you can put pretty much anything in a box that retains its aspect ratio.

    HTML:

    CSS:

    .aspectwrapper {
      display: inline-block; /* shrink to fit */
      width: 100%;           /* whatever width you like */
      position: relative;    /* so .content can use position: absolute */
    }
    .aspectwrapper::after {
      padding-top: 56.25%; /* percentage of containing block _width_ */
      display: block;
      content: '';
    }
    .content {
      position: absolute;
      top: 0; bottom: 0; right: 0; left: 0;  /* follow the parent's edges */
      outline: thin dashed green;            /* just so you can see the box */
    }
    

    The display: inline-block leaves a little extra space below the bottom edge of the .aspectwrapper box, so another element below it won't run flush against it. Using display: block will get rid of it.

    Thanks to this post for the tip!


    Another approach relies on the fact that browsers respect an image's aspect ratio when you resize only its width or height. (I'll let google generate a 16x9 transparent image for demonstration purposes, but in practice you would use your own static image.)

    HTML:

    CSS:

    .aspectwrapper {
      width: 100%;
      position: relative;
    }
    .aspectspacer {
      width: 100%; /* let the enlarged image height push .aspectwrapper's bottom edge */
    }
    .content {
      position: absolute;
      top: 0; bottom: 0; right: 0; left: 0;
      outline: thin dashed green;
    }
    

提交回复
热议问题