aspect-ratio - CSS: Cascading Style Sheets 编辑

The aspect-ratio CSS media feature can be used to test the aspect ratio of the viewport.

Syntax

The aspect-ratio feature is specified as a <ratio> value representing the width-to-height aspect ratio of the viewport. It is a range feature, meaning you can also use the prefixed min-aspect-ratio and max-aspect-ratio variants to query minimum and maximum values, respectively.

Examples

The example below is contained in an <iframe>, which creates its own viewport. Resize the <iframe> to see aspect-ratio in action.

Note that, when none of the media query conditions are true, the background will turn white because none of the below rules will be applied to the <div> inside the <iframe>. See if you can find which width and height values trigger this!

HTML

<div id='inner'>
  Watch this element as you resize your viewport's width and height.
</div>

_Example

CSS

/* Minimum aspect ratio */
@media (min-aspect-ratio: 8/5) {
  div {
    background: #9af; /* blue */
  }
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 3/2) {
  div {
    background: #9ff;  /* cyan */
  }
}

/* Exact aspect ratio, put it at the bottom to avoid override*/
@media (aspect-ratio: 1/1) {
  div {
    background: #f9a; /* red */
  }
}

used iframe and DataURL to enable this iframe could resize

HTML

<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>

CSS

iframe{
  display:block;
}

JavaScript

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
}

Result

Specifications

SpecificationStatusComment
Media Queries Level 4
The definition of 'aspect-ratio' in that specification.
Candidate RecommendationNo change.
Media Queries
The definition of 'aspect-ratio' in that specification.
RecommendationInitial definition.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:151 次

字数:5358

最后编辑:7年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文