margin-top:75% gives the box of the dummy element a height that is 75% of the aforementioned width, thus defining the aspect ratio. The key here is that a percentage value for margin-top or margin-bottom (or for padding-top or padding-bottom, for that matter) refers to the width of the containing block. Because the container is an inline-level block container, the height of the container is automatically computed as the height of the dummy element, which is based on the width of the container. Voilà, instant aspect ratio using only CSS.some text#container { display: inline-block; position: relative; width: 50%; } #dummy { margin-top: 75%; /* 4:3 aspect ratio */ } #element { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background-color: silver /* show me! */ }
dummy element用margin-top:75%, 是取parent container "寬"的75%, 把 #container 撐高, element取決對定位
via: height equal to dynamic width (CSS fluid layout)
沒有留言:
張貼留言