やりたいこと
- 固定値を使わない
- 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?