Menu
Coddy logo textTech

属性の有無と完全一致

Coddyの「CSSセレクター」コースのレッスン 12/15。

このレッスンでは、属性の存在と完全一致値セレクターについて学びます。属性セレクターは、属性の有無、または属性の正確な値に基づいて要素を選択するために使用されます。 

属性存在セレクター:

属性存在セレクターは、その値に関係なく、特定の属性を持つ要素をターゲットにします。これは、属性名を角括弧で囲んで記述します。

例:

/* Selects all elements with a "target" attribute */
[target] {
   color: blue;
}

完全一致値セレクター:

完全一致値セレクターは、特定の属性を持ち、かつその属性が特定の値である要素をターゲットにします。これは、角括弧内に属性名、続いて等号(=)、そして目的の値を記述します。

例:

/* Selects the element with "data-type" attribute having the value "important" */
[data-type="important"] {
   font-weight: bold;
}

コード例:

HTML:

<p>This is a <span target="link">link</span> element.</p>
<p data-type="important">This is an important paragraph.</p>

CSS:

[target] {
   text-decoration: underline;
}
[data-type="important"] {
   color: red;
}

これらの例は、属性の存在や正確な値に基づいて要素を選択し、それらに対応するスタイルを適用することで、CSS属性セレクターがどのように機能するかを示しています。

challenge icon

チャレンジ

簡単

属性セレクターを使用して、シンプルなHTMLフォームをスタイリングするタスクが割り当てられました。

属性セレクターを使用して、以下のスタイルを適用してください:

  1. type 属性が "text" に設定されている入力フィールドに green のボーダーを追加します。
  2. type 属性が "email" に設定されている入力フィールドの背景色を lightblue に変更します。
  3. type 属性が "password" に設定されている入力フィールドのテキストの色を red にします。

自分で試してみよう

<!DOCTYPE html>
<html>
<head>
<title>Styled Form</title>
<style>
    /* Apply styles to form fields based on attribute values */
</style>
</head>
<body>
<form>
    <label for="name">Name:</label>
    <input type="text" name="name" id="name">
    
    <label for="email">Email:</label>
    <input type="email" name="email" id="email">
    
    <label for="password">Password:</label>
    <input type="password" name="password" id="password">
    
    <input type="submit" value="Submit">
</form>
</body>
</html>

CSSセレクターのすべてのレッスン