LoginSignup
1
1

htmlのclass属性とid属性の違いについて

Last updated at Posted at 2024-04-03

はじめに

HTMLの「class属性」と「id属性」の違いについてまとめました。これらは要素を識別し、スタイルを適用したり、JavaScriptで操作したりするために使われます。この記事では、これらの属性がどのように機能し、どう使い分けるべきかの備忘です。

class属性とは

  • 同じクラス名を複数の要素に指定することができる
  • 同じクラス名を持つ要素に対して、一括でスタイルを適用することが可能

id属性とは

  • id属性は、ページ内の要素を一意に識別するために使用される
  • 同じid名を複数の要素に指定することはできない

サンプルコード

<!DOCTYPE html>
<html>
<head>
  <style>
    .red {
      color: red;
    }

    #blue {
      color: blue;
    }
  </style>
</head>
<body>
  <h1 class="red">This is a red heading.</h1>
  <p class="red">This is a red paragraph.</p>
  <p id="blue">This is a blue paragraph.</p>
</body>
</html>

結果

image.png

1
1
1

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
1
1