LoginSignup
2
3

More than 3 years have passed since last update.

CSSで正方形の背景を作るサンプル

Posted at

CSSで正方形の背景を作るサンプルを簡単に作るコードを公開したいと思います。
サンプル

課題

widthやheightで指定するのでなく、親要素に対し幅いっぱいつまり可変なwidthとheightにしたい。

コード

早速コードを書きます。

HTML
<div class="square">
</div>
CSS
.square{
  position: relative;
  width: 100%;
  padding-top: 100%;
  background: #eee; /* 好きな色に */
}

これだけでOKです。ポイントとしてはwidthとpadding-topを同じ値にする事です。
なお、padding-topはpadding-bottomにしても良いです。

応用

この正方形の背景の中に文字を入れたい時は、position:absoluteを使っていきます。

HTML
<div class="square">
  <p class="p-center">SQUARE</p>
</div>
CSS
.square{
  position: relative;
  width: 100%;
  padding-top: 100%;
  background: #eee; /* 好きな色に */
}
.p-center{
  position: absolute;
  top: 50%;
  left: 0;
  transform: translateY(-50%);
  width: 100%;
  text-align: center;
}

こんな感じで、めちゃ楽勝です。

2
3
0

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
2
3