--- title: aspect-ratio slug: Web/CSS/@media/aspect-ratio translation_of: Web/CSS/@media/aspect-ratio ---
aspect-ratio
CSS 媒体属性 可以用来测试 {{glossary("viewport")}} 的宽高比。
宽高比属性被指定为{{cssxref("<ratio>")}}值来代表viewport的宽高比。其为一个范围,这意味着你可以使用min-aspect-ratio
和max-aspect-ratio
分别查询最小和最大的值。
下面的例子包含一个 {{htmlElement("iframe")}} ,拥有它自身的viewport。调整的<iframe>
宽高来观察aspect-ratio
的变化。
<div id='inner'> Watch this element as you resize your viewport's width and height. </div>
/* 最小宽高比 */ @media (min-aspect-ratio: 8/5) { div { background: #9af; /* blue */ } } /* 最大宽高比 */ @media (max-aspect-ratio: 3/2) { div { background: #9ff; /* cyan */ } } /* 明确的宽高比, 放在最下部防止同时满足条件时的覆盖*/ @media (aspect-ratio: 1/1) { div { background: #f9a; /* red */ } }
used iframe and DataURL to enable this iframe could resize
<label id="wf" for="w">width:165</label> <input id="w" name="w" type="range" min="100" max="250" step="5" value="165"> <label id="hf" for="w">height:165</label> <input id="h" name="h" type="range" min="100" max="250" step="5" value="165"> <iframe id="outer" src="data:text/html,<style> @media (min-aspect-ratio: 8/5) { div { background: %239af; } } @media (max-aspect-ratio: 3/2) { div { background: %239ff; } } @media (aspect-ratio: 1/1) { div { background: %23f9a; } }</style><div id='inner'> Watch this element as you resize your viewport's width and height.</div>"> </iframe>
iframe{ display:block; }
outer.style.width=outer.style.height="165px" w.onchange=w.oninput=function(){ outer.style.width=w.value+"px" wf.textContent="width:"+w.value } h.onchange=h.oninput=function(){ outer.style.height=h.value+"px" hf.textContent="height:"+h.value }
{{ EmbedLiveSample('_Example', '300px', '400px') }}
Specification | Status | Comment |
---|---|---|
{{SpecName('CSS4 Media Queries', '#aspect-ratio', 'aspect-ratio')}} | {{Spec2('CSS4 Media Queries')}} | No change. |
{{SpecName('CSS3 Media Queries', '#aspect-ratio', 'aspect-ratio')}} | {{Spec2('CSS3 Media Queries')}} | Initial definition. |
{{Compat("css.at-rules.media.aspect-ratio")}}