可以在视口中放置一个方形 div 并使其居中并始终保持 aspect ratio according to width and height ?
div
要求 :
只有CSS
正方形的大小必须适应视口的最小尺寸(宽度或高度),而不管视口的方向(横向或纵向) .
正方形必须在视口中以水平方向和垂直方向居中
例:
我结合了@ ken-sharpe和@easwee的优秀答案来创建非方形宽高比的版本:https://codepen.io/anon/pen/GyqopP
div { position: absolute; top:0;bottom:0; left:0;right:0; margin: auto; width: 100vw; height: 50vw; background: #326384; } @media (min-aspect-ratio: 2/1) { div { width: 200vh; height: 100vh; background-color:green; } }
使用这样的东西
.container{ display:block; background:#f2f2f2; } .square{ width:50%; padding-top:50%; margin: auto; background:#e5e5e5; }
DEMO
__847213_在视口中,您可以使用一个HTML标记:
vmin视口高度和宽度之间最小值的1/100 . (来源:MDN)
position: absolute
margin: auto;
DEMO (调整窗口高度和宽度以查看其运行情况)
根据 width and height 保持其纵横比
保持在视口中心和verticaly中心
永远不会溢出视口
对于IE9支持IE10(canIuse)支持 vmin 单位,你需要使用 vm 单位的后备而不是 vmin ,如下所示:
vmin
vm
width: 100vm; /* <-- for IE9 */ height: 100vm; /* <-- for IE9 */ width: 100vmin; height: 100vmin;
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>
您可以使用vw & vh units(视口百分比长度)来确定响应方块的大小 .
检查浏览器支持:http://caniuse.com/viewport-units
实现水平和垂直缩放的解决方案
实时样本页面:http://sample.easwee.net/responsive-square/
.container { display:table; width:100%; height:100%; } .container-row { display:table-row; } .container-cell { display:table-cell; vertical-align:middle; text-align:center; } .square { display:inline-block; background:red; border: 3px solid blue; } @media(orientation:landscape) { .square { width: 100vh; height: 100vh; } } @media(orientation:portrait) { .square{ width: 100vw; height: 100vw; } }
<div class="container"> <div class="container-row"> <div class="container-cell"> <div class="square"></div> </div> </div> </div>
4 回答
我结合了@ ken-sharpe和@easwee的优秀答案来创建非方形宽高比的版本:https://codepen.io/anon/pen/GyqopP
使用这样的东西
DEMO
__847213_在视口中,您可以使用一个HTML标记:
position: absolute
和margin: auto;
用于居中DEMO (调整窗口高度和宽度以查看其运行情况)
特点:
根据 width and height 保持其纵横比
保持在视口中心和verticaly中心
永远不会溢出视口
浏览器支持:
对于IE9支持IE10(canIuse)支持
vmin
单位,你需要使用vm
单位的后备而不是vmin
,如下所示:完整代码:
您可以使用vw & vh units(视口百分比长度)来确定响应方块的大小 .
检查浏览器支持:http://caniuse.com/viewport-units
实现水平和垂直缩放的解决方案
实时样本页面:http://sample.easwee.net/responsive-square/