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

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

问题描述

是否可以在视口中放置一个正方形 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?

要求:

  • 只有 CSS
  • 无论视口的方向(横向或纵向)如何,正方形的大小都必须适应视口的最小尺寸(宽度或高度).
  • 正方形必须在视口中水平和垂直居中

示例:

推荐答案

要在视口中根据宽度和高度保持 div 的纵横比,您可以使用一个 HTML 标签:

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

  1. vmin 用于调整大小的单位:<块引用>

    vmin 视口高度和宽度之间最小值的 1/100.
    (来源:MDN)

  1. vmin units for the sizing :

  • position: absolutemargin: auto; 用于居中
  • vmin 1/100th of the minimum value between the height and the width of the viewport.
    (source : MDN)

    DEMO(将窗口高度和宽度调整为看到它在行动)

  • position: absolute and margin: auto; for the centering
    • 根据宽度和高度
    • 保持纵横比
    • 水平和垂直保持在视口中心
    • 永远不会溢出视口

    vmin 单位由 IE10+ (canIuse) 支持以支持 IE9,您需要像这样使用 vm 单位而不是 vmin 的回退:

    • keeps it's aspect ratio according to width and height
    • stays centered in viewport horizontaly and verticaly
    • never overflows the viewport
    vmin units are supported by IE10+ (canIuse) for IE9 support, you need to use a fallback with vm units instead of vmin like this :

    完整代码:

    
    

    
    
    任何你想要的内容

    <div>whatever content you wish</div>

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

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