--- title: aspect-ratio slug: Web/CSS/aspect-ratio translation_of: Web/CSS/aspect-ratio --- <div>{{CSSRef}}</div> <p><strong><code>aspect-ratio</code></strong> <a href="/en-US/docs/CSS">CSS</a> 属性为box容器规定了一个<strong>期待的纵横比</strong>,这个纵横比可以用来计算自动尺寸以及为其他布局函数服务。</p> <pre class="brush:css no-line-numbers notranslate">aspect-ratio: 1 / 1; /* 全局值 */ aspect-ratio: inherit; aspect-ratio: initial; aspect-ratio: unset; </pre> <h3 id="数值">数值</h3> <dl> <dt>{{cssxref("<auto>")}}</dt> <dd>具有固有宽高比的替换元素将使用该宽高比,否则该内容框没有首选的宽高比。 涉及固有宽高比的尺寸计算始终与内容框尺寸一起使用。</dd> <dt>{{cssxref("<ratio>")}}</dt> <dd>内容框首选的宽高比是通过 <code>width</code> / <code>height</code> 定义的。当为内容框定义 <code>box-sizing</code> 之后,尺寸的计算就可以通过指定宽高比来实现。</dd> </dl> <h2 id="正式定义">正式定义</h2> <p>{{cssinfo}}</p> <h2 id="正式语法">正式语法</h2> {{csssyntax}} <h2 id="示例">示例</h2> <h3 id="纵横比数值例子">纵横比数值例子</h3> <pre class="brush: css notranslate">aspect-ratio: 1 / 1; aspect-ratio: 16 / 9; </pre> <h2 id="将宽度和高度关联到宽高比">将宽度和高度关联到宽高比</h2> <p>浏览器内部已经为替换的元素和其他接受 <code>width</code> 和 <code>height</code> 的元素添加了 <code>aspect-ratio</code>。这些可以在浏览器的UA样式表中看到。</p> <p>在 Firefox 中,内部样式表看起来如下:</p> <pre class="brush: css notranslate">img, input[type="image"], video, embed, iframe, marquee, object, table { aspect-ratio: attr(width) / attr(height); }</pre> <p>您可以在 <a href="https://www.smashingmagazine.com/2020/03/setting-height-width-images-important-again/">为图片设置宽高仍然重要gain</a> 一文中了解更多与这个功能有关的内容。</p> <h2 id="规范">规范</h2> <table class="standard-table"> <thead> <tr> <th scope="col">规范</th> <th scope="col">状态</th> <th scope="col">注释</th> </tr> </thead> <tbody> <tr> <td>{{SpecName('CSS4 Sizing', '#aspect-ratio', 'aspect-ratio')}}</td> <td>{{Spec2('CSS4 Sizing')}}</td> <td>初始定义</td> </tr> </tbody> </table> <h2 id="Browser_compatibility" name="Browser_compatibility">浏览器兼容性</h2> <p>{{Compat("css.properties.aspect-ratio")}}</p> <h2 id="相关阅读">相关阅读</h2> <ul> <li><a href="/en-US/docs/Web/Media/images/aspect_ratio_mapping">关联媒体容器元素的宽度与高度到它的宽高比上</a></li> <li><a href="https://www.smashingmagazine.com/2019/03/aspect-ratio-unit-css/">为 CSS 设计一个宽高比单元</a></li> </ul>