根据宽度和高度保持宽高比 [英] Maintain aspect ratio according to width and height

查看:158
本文介绍了根据宽度和高度保持宽高比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在视口中安装并居中一个正方形 div ,并始终根据宽度和高度保持宽高比

要求:




  • 仅限CSS

  • 必须适应视口的最小尺寸(宽度或高度),而不管视口的方向(横向或纵向)。

  • 正方形必须居中horizo​​ntaly和verticaly
  • //i.stack.imgur.com/nKS55.pngalt =根据视口的宽度和高度保持宽高比>

    解决方案



      要在视口中根据宽度和高度维持div的宽高比 >

    1. vmin 单位:


      vmin 在视口的高度和宽度之间的最小值。

      (来源: MDN < a>)



    2. position:absolute :auto; 用于居中

    DEMO (调整窗口高度和宽度以查看其动作)



    功能:




    • 根据宽度和高度保持宽高比
    • $ b $


    浏览器 支持:



    vmin 单位支持IE10 +( canIuse )对于IE9支持,您需要使用 vm 单位而不是 vmin 像这样:

      width:100vm; / *<  -  for IE9 * / 
    height:100vm; / * < - 对于IE9 * /
    width:100vmin;
    height:100vmin;



    完整代码:



    =snippetdata-lang =jsdata-hide =true>

      body {margin:0; / *防止滚动条* /} div {/ *长宽比* / height:100vm; width:100vm; / * IE9 fallback * / width:100vmin;高度:100vmin; / *居中* / position:absolute; top:0; bottom:0; left:0; right:0; margin:auto; / * styleing * / background:gold;}  

      div>您希望的任何内容< / div>  


It is possible to fit and center a square div in the viewport and always maintain it's aspect ratio according to width and height?

Requirements :

  • only CSS
  • the size of the square must adapt to the smallest dimension (width or height) of viewport regardless of the orientation (landscape or portrait) of the viewport.
  • the square must be centered horizontaly and verticaly in the viewport

Example:

解决方案

To maintain the aspect ratio of a div according to width and height in the viewport, you can uses one HTML tag with:

  1. vmin units for the sizing :

    vmin 1/100th of the minimum value between the height and the width of the viewport.
    (source : MDN)

  2. position: absolute and margin: auto; for the centering

DEMO (resize both window height and width to see it in action)

Features :

  • keeps it's aspect ratio according to width and height
  • stays centered in viewport horizontaly and verticaly
  • never overflows the viewport

Browser support :

vmin units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback with vm units instead of vmin like this :

width: 100vm; /* <-- for IE9 */
height: 100vm; /* <-- for IE9 */
width: 100vmin; 
height: 100vmin;

Full code:

body {
  margin:0; /* To prevent scrollbars */
}

div{
  /* Aspect ratio */
  height:100vm; width:100vm; /* IE9 fallback */
  width: 100vmin; 
  height: 100vmin;
  /*Centering */
  position: absolute;
  top:0;bottom:0;
  left:0;right:0;
  margin: auto;
  /* styling */
  background: gold;
}

<div>whatever content you wish</div>

这篇关于根据宽度和高度保持宽高比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆