2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【CSS備忘録】calc() 関数の使い方と実務でよく使うパターンまとめ【柔軟なレイアウトに便利】

2
Posted at

はじめに

本記事では、CSSでよく使う calc() 関数について、自分用の備忘録としてまとめます。
特に 異なる単位の混在レスポンシブ対応 など、実務でもよく使うパターンを紹介します。


①calc() 関数とは?

CSS内で数値を計算するための関数です。
例えば、「全体の幅から30pxだけ引いたサイズにしたい」といった場合に使います。

width: calc(100% - 30px);

②基本構文

プロパティ: calc(数値A 演算子 数値B);
  • 演算子は + - * / が使えます
  • 異なる単位(px, %, emなど)を組み合わせ可能
  • 演算子の前後にスペースが必須

③よく使うパターン

1.全体の横幅から余白を引く

.container {
    width: calc(100% - 40px);
}

→全体幅から余白分だけ引いたレイアウトにしたいとき。

2.ヘッダーを除いた高さ指定

.main {
    height: calc(100vh - 60px);
}

→全画面表示からヘッダー分(60px)を差し引いた高さを指定できます。

3.中央寄せで幅 ⁺ 余白を調整

.button {
    margin: 0 auto;
    width: calc(50% + 100px);
}

→画面サイズに応じてボタンを中央に調整したいときに便利。

4.複数列レイアウトで余白調整

.card {
    margin: calc(33.333% - 20px);
    width: 10px;
}

→3カラム構成などで隙間の幅を考慮したサイズ指定が可能。

④注意点

IMG_7817.jpeg

⑤まとめ

  • calc() は異なる単位の組み合わせや、動的なサイズ調整が必要な場面に有効
  • レスポンシブ対応、中央寄せ、カードUIのレイアウトなどでよく登場
  • CSSの中で電卓が使えると思うと便利!
2
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?