LoginSignup
30

More than 5 years have passed since last update.

CSSだけで正方形を作る

Last updated at Posted at 2014-11-27

やりたいこと

  • 固定値を使わない
  • JavaScriptを使わない
  • ウィンドウサイズやレイアウトが変わっても正方形を自動で維持する

ブレイクスルー

  • padding-bottomはy方向に影響するプロパティだが、そこで%指定するとx方向を基準にした描画が行われる

Example

この赤い正方形をCSSだけで作る。

Screen Shot 2014-11-27 at 19.33.33.png


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?

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30