やりたいこと
- 固定値を使わない
- JavaScriptを使わない
- ウィンドウサイズやレイアウトが変わっても正方形を自動で維持する
ブレイクスルー
-
padding-bottomはy方向に影響するプロパティだが、そこで%指定するとx方向を基準にした描画が行われる
Example
この赤い正方形をCSSだけで作る。
index.jade
doctype html
html
head
link(href="styles/main.css" rel="stylesheet")
body
.square-wrapper
.spacer
.content
main.stylus
.square-wrapper
position relative
width 10%
.spacer
width 100%
padding-bottom 100%
.content
position absolute
top 0
right 0
bottom 0
left 0
background red
この場合、.spacerは.square-wrapperの幅と同じ高さが確保される。
そうすると.square-wrapperの高さも拡張されるため、結果として.contentも正方形になる。
参考URL
How can I create a perfectly square DIV where height is equal to viewport?
