cssText でまとめてスタイルを設定する

cssText は、要素のインラインスタイルを文字列としてまとめて取得・設定するプロパティです。複数のスタイルを一度に設定したいときに便利です。

基本的な使い方

const element = document.getElementById('box');

// 複数のスタイルを一度に設定
element.style.cssText = 'color: red; font-size: 20px; padding: 10px;';

CSS の書き方そのままで設定できるのがポイントです。ハイフン区切りのプロパティ名(font-size など)がそのまま使えます。

cssText を取得する

現在のインラインスタイルを文字列として取得できます。

<div id="box" style="color: red; font-size: 20px;">テスト</div>
const box = document.getElementById('box');
console.log(box.style.cssText); // "color: red; font-size: 20px;"

既存のスタイルは上書きされる

cssText を設定すると、既存のインラインスタイルはすべて上書きされます。

element.style.color = 'red';
element.style.backgroundColor = 'blue';

// cssText で設定すると、上の color と backgroundColor は消える
element.style.cssText = 'font-size: 24px;';

追加したい場合は、既存の値を連結します。

element.style.cssText += 'font-size: 24px;';

実際に動かしてみよう

HTML
CSS
JavaScript
<div id="box">スタイルを変更</div>
<button id="style1">スタイル1</button>
<button id="style2">スタイル2</button>
<button id="style3">スタイル3</button>
<p>cssText: <code id="display"></code></p>
#box {
  padding: 20px;
  margin-bottom: 10px;
  transition: all 0.3s;
}
const box = document.getElementById('box');
const display = document.getElementById('display');

function updateDisplay() {
  display.textContent = box.style.cssText || '(なし)';
}

document.getElementById('style1').addEventListener('click', () => {
  box.style.cssText = 'background: #4caf50; color: white; border-radius: 8px;';
  updateDisplay();
});

document.getElementById('style2').addEventListener('click', () => {
  box.style.cssText = 'background: #2196f3; color: white; font-size: 24px;';
  updateDisplay();
});

document.getElementById('style3').addEventListener('click', () => {
  box.style.cssText = 'background: #ff9800; padding: 40px; text-align: center;';
  updateDisplay();
});

updateDisplay();

個別設定との比較

cssText

複数のスタイルを一度に設定。既存スタイルは上書き

個別設定(style.color など)

1つずつ設定。他のスタイルは保持される

使いどころ

テーマの切り替え

複数のスタイルをまとめて変更したいとき

スタイルのリセット

空文字を設定してインラインスタイルを全削除

// インラインスタイルをすべて削除
element.style.cssText = '';

setAttribute との関係

cssTextsetAttribute('style', ...) は同じ結果になります。

// 同じ結果
element.style.cssText = 'color: red;';
element.setAttribute('style', 'color: red;');

cssText のほうが JavaScript らしい書き方ですが、どちらを使っても構いません。