この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:8
ページ更新者:guest
更新日時:2026-06-11 07:07:02

タイトル: .css()
SEOタイトル: jQuery .css() 完全ガイド(取得 / 設定 / 一括 / CSS Variables / 現代の代替)

この記事の要点
  • 取得: $("p").css("color") → ブラウザが計算した最終値(getComputedStyle)
  • 設定: $("p").css("color", "red")。複数なら {} 渡し
  • プロパティ名は camelCase / kebab-case 両方 OK(backgroundColor / "background-color"
  • 関数で動的設定: function(i, val) { return ... } で要素ごとに違う値
  • CSS Variables: $("p").css("--my-var", "red") (jQuery 3.7+)
  • 現代の代替: element.style.color = "red" / getComputedStyle() / classList 切替が主流

.css() の基本

jQuery オブジェクトに対して CSS プロパティを取得または設定するメソッド。

// ===== 取得 =====
// 1 つのプロパティを取得(最初の要素のみ)
$('p').css('color');         // → "rgb(0, 0, 0)" のようなブラウザ計算値
$('p').css('font-size');     // → "16px"
$('p').css('width');         // → ピクセル値で取得("100px" 等)

// ===== 設定 =====
// 単一プロパティ
$('p').css('color', 'red');

// 複数プロパティ(オブジェクト)
$('p').css({
    color: 'red',
    fontSize: '20px',
    backgroundColor: '#eee'
});

// kebab-case もOK(クォート必須)
$('p').css({
    'background-color': '#eee',
    'font-weight': 'bold'
});

プロパティ名: camelCase と kebab-case

CSScamelCasekebab-case
background-colorbackgroundColor'background-color'
font-sizefontSize'font-size'
margin-topmarginTop'margin-top'
z-indexzIndex'z-index'

オブジェクト渡しで kebab-case を使う場合は必ずクォートで囲みます(JS の識別子に - は使えないため)。

関数で動的に設定

要素ごとに異なる値を計算して設定したい場合、第 2 引数に関数を渡せます。

// 各要素のインデックスに応じて幅を設定
$('.box').css('width', function (i, currentVal) {
    return (i + 1) * 100 + 'px';
});
// 1 つ目: 100px, 2 つ目: 200px, 3 つ目: 300px

// 現在値を加工して返す
$('p').css('font-size', function (i, val) {
    return parseFloat(val) * 1.2 + 'px';
});
// すべての p の font-size を 1.2 倍に

幅 / 高さ取得時の単位

.css('width') はブラウザが計算した最終値を返すため、常に px 単位の文字列です:

$('#box').css('width');
// → "320px" のような文字列

// 数値で欲しいなら .width() を使う方が便利
$('#box').width();
// → 320 (number、padding/border 含まない)

// または parseFloat
parseFloat($('#box').css('width'));
// → 320

CSS Variables(カスタムプロパティ)

jQuery 3.7+ では CSS Variables(--my-var など)も .css() で扱えます:

// 設定
$(document.documentElement).css('--brand', '#ff5722');
$(':root').css('--brand', '#ff5722');

// 取得
$(':root').css('--brand');
// → " #ff5722" 等(先頭空白含む場合あり、要 trim)

// 取得時は getPropertyValue で取った方が確実
$('#box')[0].style.getPropertyValue('--brand');

// すべての要素に動的に
$('.card').css('--card-bg', '#fafafa');

現代の Vanilla JS 代替

2026 年現在、新規プロジェクトでは jQuery を使わずに Vanilla JS で書くのが主流です。

取得: getComputedStyle

const el = document.querySelector('p');

// 計算された最終値
const styles = window.getComputedStyle(el);
console.log(styles.color);        // "rgb(0, 0, 0)"
console.log(styles.fontSize);     // "16px"
console.log(styles.width);        // "320px"

// CSS Variables 取得
const brand = getComputedStyle(document.documentElement)
              .getPropertyValue('--brand').trim();

設定: element.style

const el = document.querySelector('p');

// 単一プロパティ
el.style.color = 'red';
el.style.fontSize = '20px';

// 複数(Object.assign)
Object.assign(el.style, {
    color: 'red',
    fontSize: '20px',
    backgroundColor: '#eee'
});

// CSS Variables(setProperty 必須)
el.style.setProperty('--brand', '#ff5722');

// 全要素
document.querySelectorAll('.box').forEach((el, i) => {
    el.style.width = (i + 1) * 100 + 'px';
});

推奨: classList で切替

JS で直接スタイルを書くより、CSS でクラス定義 → JS は classList で切替が保守性で勝ります:

// ❌ 直接 style
el.style.display = 'none';
el.style.color = 'red';

// ✅ class 切替
el.classList.add('hidden');
el.classList.toggle('active');
el.classList.remove('error');

// 対応 CSS
// .hidden { display: none; }
// .active { color: blue; }
// .error  { color: red; }

jQuery → Vanilla JS 対応表

jQueryVanilla JS
$(el).css('color')getComputedStyle(el).color
$(el).css('color', 'red')el.style.color = 'red'
$(el).css({...})Object.assign(el.style, {...})
$(el).css('--var', 'x')el.style.setProperty('--var', 'x')
$(els).css('width', fn)els.forEach((el, i) => el.style.width = fn(i))

パフォーマンス注意点

  • 大量要素に .css() を連続で呼ぶ → reflow 多発 → 重い
  • クラス切替でまとめてスタイル変更する方が高速
  • 取得(.css('width') 等)は強制 reflowを起こす
  • 設定 → 取得 → 設定 のループは要注意(Layout Thrashing)

FAQ

Q: $(el).css('display', 'none')$(el).hide() の違い
A: .hide() は内部で display: none をセットしつつ、元の display 値を data- に保存します。.show() で復元するため。.css() 直接設定では復元できません。

Q: !important を付けたい
A: .css() では付けられません。el[0].style.setProperty('color', 'red', 'important') を使うか、クラス切替を推奨。

Q: CSS のクラス名を動的に追加したい
A: $(el).addClass('foo') / .removeClass('foo') / .toggleClass('foo')。jQuery 不要なら el.classList.add/remove/toggle