CSSのcalcでroundを使用

CSSのcalcでroundを使用

calc() 関数は、CSSで動的な長さやサイズを計算するための便利なツールですが、round() 関数は calc() とは直接組み合わせて使うことはできません。
round() 関数は、CSSにおいては使用できず、主に JavaScript の関数として提供されています。

calc() 関数は、次のように基本的な算術演算をサポートします:

  • 足し算 (+)
  • 引き算 (-)
  • 掛け算 (*)
  • 割り算 (/)

これにより、サイズや位置などを動的に計算できます。
例えば、次のように使います:

.test-container {
  width: calc(100% - 20px);
  height: calc(50vh - 10px);
}

ここで、calc(100% - 20px) は、要素の幅を親要素の幅から 20px 引いたサイズに設定します。
同様に、calc(50vh - 10px) は、ビューポートの高さの50%から10pxを引いた高さを指定します。

しかし、round() のような数値の丸め機能は、CSSの calc() 関数内では使用できません。
このような処理は、JavaScriptを使って実装する必要があります。
以下は、JavaScriptで数値を丸めて、CSSスタイルに適用する方法の例です:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="styles.css">
  <title>CSS calc and round Example</title>
</head>
<body>
  <div class="test-container">
    Content goes here
  </div>
  <script src="script.js"></script>
</body>
</html>

CSS (styles.css)

.test-container {
  width: 100%;
  height: 100vh;
  background-color: lightblue;
}

JavaScript (script.js)

document.addEventListener('DOMContentLoaded', () => {
  const container = document.querySelector('.test-container');

  // 画面の幅と高さを取得
  const viewportWidth = window.innerWidth;
  const viewportHeight = window.innerHeight;

  // 幅と高さを計算
  const calculatedWidth = viewportWidth * 0.8; // 80% of viewport width
  const calculatedHeight = viewportHeight * 0.6; // 60% of viewport height

  // 数値を丸め
  const roundedWidth = Math.round(calculatedWidth);
  const roundedHeight = Math.round(calculatedHeight);

  // スタイルを適用
  container.style.width = `${roundedWidth}px`;
  container.style.height = `${roundedHeight}px`;
});

このスクリプトは、画面の幅と高さの80%と60%を計算し、それらの値を丸めてから、.test-container の幅と高さに設定します。

この方法で、CSSの calc() では直接処理できない丸め処理を行い、柔軟なデザインを実現することができます。