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?

JavaScriptでCSSを設定する方法あれこれ

2
Posted at

JavaScriptでCSSの値を動的に変更したい

ゲームを作っていて、設定した値によってレイアウトを変えることをしたく以下のようなCSSをJavaScriptで値を変えたいと思い調べたのでメモ。

#my-grid {
  display: grid;
  grid-template-columns: repeat(4, 80px);
  grid-template-rows: repeat(4, 80px);
  height: 320px;
  width: 320px;
}

これをひとまずそのままJavaScriptで設定してみようと思います。

方法1: cssText を使う

CSSの書き方をそのままコピペ感覚で使えるので、複数まとめて設定したい時におすすめの手法です。

// 1. 対象のエレメントを取得する(IDが 'my-grid' だと仮定します)
const element = document.getElementById('my-grid');

// 2. cssTextを使ってまとめてスタイルを流し込む
element.style.cssText = '
  display: grid;
  grid-template-columns: repeat(4, 80px);
  grid-template-rows: repeat(4, 80px);
  height: 320px;
  width: 320px;
';

方法2: プロパティを1つずつ指定する

JavaScriptのプログラムの中で、条件によって縦横のサイズだけ変えたいというような場合は、1つずつ個別に設定するこちらの書き方を使います。

// 1. 対象のエレメントを取得する
const element = document.getElementById('my-grid');

// 2. 1つずつスタイルを当てる
element.style.display = 'grid';
// 💡 CSSのハイフン(-)は消して、次の文字を大文字(キャメルケース)にするのがJSのルール
element.style.gridTemplateColumns = 'repeat(4, 80px)';
element.style.gridTemplateRows = 'repeat(4, 80px)';
element.style.height = '320px';
element.style.width = '320px';

本題:方法1の方法でCSSの値を変数で指定する

CSSを囲むのにシングルクォーテーション(')ではなく、バッククォート( `)を使います。
JavaScriptでは、バッククォートで囲んだ文字列(テンプレートリテラルと呼びます)の中では、${変数名} と書くことで、JavaScriptの変数や計算式をそのまま直接埋め込むことができるんです。

// 1. 変数で数値を定義する
const colCount = 4;        // 列数
const rowCount = 4;        // 行数
const cellSize = 80;       // 1マスのサイズ(px)

// (全体のサイズを自動計算させることもできます)
const gridWidth = colCount * cellSize;  // 320
const gridHeight = rowCount * cellSize; // 320

// 対象のエレメントを取得する(IDが 'my-grid' だと仮定します)
const element = document.getElementById('my-grid');

// ${変数名} を使って、CSSの中に数値を埋め込む
element.style.cssText = `
  display: grid;
  grid-template-columns: repeat(${colCount}, ${cellSize}px);
  grid-template-rows: repeat(${rowCount}, ${cellSize}px);
  height: ${gridHeight}px;
  width: ${gridWidth}px;
`;

本題:方法2の方法でCSSの値を変数で指定する

文字列結合の要領で変数と文字列を結合します。

// 上記例と同じなので省略

// 文字列結合
element.style.width = gridWidth + 'px';

// テンプレートリテラルを使ってもOK
element.style.height = `${gridHeight}px`;

CSSのエレメント(<style>)を埋め込む

最終的に<style>要素を生成して埋め込む方法が、無駄にIDやclassを指定しなくてもよいのではという結論に落ち着いて以下の方法で実装しました。

// 1. 変数で数値を定義する
const colCount = 4;        // 列数
const rowCount = 4;        // 行数
const cellSize = 80;       // 1マスのサイズ(px)

// (全体のサイズを自動計算させることもできます)
const gridWidth = colCount * cellSize;  // 320
const gridHeight = rowCount * cellSize; // 320

const styleElement = document.createElement('style');

// 2. ${変数名} を使って、CSSの中に数値を埋め込む
styleElement.textContent = `
  #my-grid {
    display: grid;
    /* 変数を埋め込む */
    grid-template-columns: repeat(${colCount}, ${cellSize}px);
    grid-template-rows: repeat(${rowCount}, ${cellSize}px);
    height: ${gridHeight}px;
    width: ${gridWidth}px;
  }
`;

document.head.appendChild(styleElement);

個別の時には方法2で、CSSをたくさん変更するときにはこの方法でやろうかな。

2
1
3

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?