cssdream / cssgrace

从今天起,写简单优雅面向未来的 CSS。From now on,writing brief,elegant,future-oriented CSS.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

About aspect-ratio CSS property

yisibl opened this issue · comments

CSS Grace 考虑实现 CSS aspect-ratio polyfill。

CSS Aspect Ratio Module Level 1 Personal Draft

1. Introduction(介绍)

This section is not normative.
本章节不具有规范叙述。

aspect-ratio 属性用来定义元素宽高比例,可以灵活的解决视频(video),图片等媒体元素的等比缩放问题。

1.1. Overview(概述)

This section is not normative.
本章节不具有规范叙述。

以视频为例,常见的有 16/9,4/3 等常见尺寸,通过 aspect-ratio 属性可以非常容易的设定视频的宽高比。

以下提到的「最小或最大尺寸」是指 min-width/min-height 或 max-width/max-height。

示例1:

当父元素 .foo 宽度或高度改变时,video 始终保持 16/9 的宽高比。

.foo > video {
  aspect-ratio: 16/9;
}

2. The aspect-ratio Property

Name: aspect-ratio
Value: auto | none | <ratio>
Initial: auto
Applies to: block-level elements
Inherited: no
Media: visual
Computed value: same as specified value
Animatable: Yes

auto

auto 值将自动获取元素默认的宽高比。

none

aspect-ratio 不生效,没有效果。

<ratio>

是一个比值,以/分割,/的左右可以有0个或�多个空白符(参见 CSS 空白符定义)。
必须大于 0 ,否则视为语法错误。
如果同时定义了最小或最大尺寸限制,应当以它们为准来计算元素的实际宽高。

示例 2:

设置了宽高比的元素会先继承父元素的宽度,然后使用设置的比例计算高度。

.foo {
  width: 800px;
}
.foo > video {
  width: auto;
  height: auto; /* 800 * 0.75 =  600*/
  aspect-ratio: 4/3; /* 0.75 */
}

height 最终计算值为 600px。

示例 3:

.foo {
  width: 500px;
}
.foo > video {
  width: auto;
  height: auto; /* 500 / 0.5 =  1000*/
  max-height: 500px;
  aspect-ratio: 2/1;
}

优先保证 max-height 的设置,宽度会重新计算:

width = 500 / 0.5 = 1000px

主流浏览器已经实现,不再考虑。