CSSelectors をマスターする: 例を含む完全ガイド

王林
リリース: 2024-09-07 00:00:27
オリジナル
614 人が閲覧しました

Mastering CSSelectors: A Complete Guide with Examples

導入

この記事では、CSS3 セレクターについて説明します。CSS3 セレクターは、記述量を減らしてより多くのことを行いたい人にとって非常に強力なツールです。始めたばかりの場合でも、スキルを磨いている場合でも、このガイドでは基本から高度な内容まで説明します。

CSS スキルをレベルアップする準備はできましたか?始めましょう!

基本的な CSS3 セレクター

セレクターは、HTML ツリーから特定の要素を選択するために使用するツールです。基本 CSS3 セレクターは、名前が示すように、すべての開発者がツールキットに含める必要がある基本的なセレクターです。これらには、 TypeClassIDUniversal 、および Attribute セレクターが含まれます。それぞれについて詳しく見ていきましょう。

タイプセレクター

これらのセレクターは、タグ名に基づいて HTML 要素をターゲットにします。たとえば、p { color: blue; } は、すべての段落要素のスタイルを青色に設定します。

クラスセレクター

これらのセレクターは、クラス属性に基づいて HTML 要素をターゲットにします。たとえば、.alert { color: red; } クラス「alert」を持つすべての要素のスタイルを赤色に設定します。

ID セレクター

これらのセレクターは、特定の id 属性を持つ一意の要素をターゲットとしています。たとえば、 #navbar { 背景色: 黒; } は、ID「navbar」の要素を黒の背景でスタイル設定します。

ユニバーサル セレクター

これらのセレクターは、ページ上のすべての要素を対象としています。たとえば、* { マージン: 0; } は、ページ上のすべての要素からマージンを削除します。

属性セレクター

これらのセレクターは、属性と値に基づいて要素をターゲットにします。たとえば、a[href="https://google.com"] { color: blue; } は、Google に向かうすべてのリンクのスタイルを青色に設定します。

短いコーディング例

  • タイプセレクター : h1 { color: green; } は、すべての h1 ヘッダーを緑色にします。

  • タイプセレクター : p { font-size: 16px; } は、すべての段落要素 (

    ) を選択し、フォント サイズを 16 ピクセルに設定します。

  • クラスセレクター : .info { font-size: 18px; } は、クラス「info」を持つすべての要素のフォント サイズを 18px に設定します。

  • クラスセレクター : .highlight { 背景色: yellow; } は、クラス「ハイライト」を持つすべての要素を選択し、背景色を黄色に設定します。

  • ID セレクター : #footer { パディング: 20px; } は、ID が「footer」の要素に 20px のパディングを追加します。

  • ID セレクター : #header { height: 60px; } は、ID「header」を持つ要素を選択し、その高さを 60 ピクセルに設定します。

  • ユニバーサル セレクター : * { font-family: Arial、sans-serif; } は、すべての要素のフォントを Arial に設定します。

  • ユニバーサル セレクター : * { box-sizing: border-box; } は、ページ上のすべての要素を選択し、ボックス サイズ プロパティを「border-box」に設定します。これには、要素の幅と高さの合計にパディングとボーダーが含まれます。

  • 属性セレクター : img[alt] { border: 2px 単色黒; } は、alt 属性を持つすべての画像に境界線を追加します。

  • 属性セレクター : input[type="text"] { width: 100%; } - これにより、タイプが「text」のすべての入力要素が選択され、その幅が親コンテナの 100% に設定されます。

疑似クラスセレクター

疑似クラス セレクターは、タイプ、属性、クラスではなく、ドキュメント構造内での状態や位置に基づいて要素を選択し、スタイル設定できるようにする CSS の強力な機能です。これらは、ダイナミックでレスポンシブなデザインを作成するのに役立ちます。

動的擬似クラス

動的疑似クラスには、ユーザーの操作に基づいて変化するスタイルが含まれています。たとえば、a:hover { color: red; となります。 } にカーソルを置くと、リンクの色が赤に変わります。

構造擬似クラス

構造擬似クラスは、ドキュメント構造内の位置に基づいて要素を選択します。たとえば、 p:first-child { font-weight:bold; } は、含まれる要素内の最初の段落を太字にします。

否定擬似クラス

否定擬似クラス :not() は、選択から特定の要素を除外します。たとえば、 div:not(.highlight) { 背景色: yellow; } は、クラス「highlight」を持つ div を除くすべての div の背景色を黄色に変更します。

入力疑似クラス

入力疑似クラスは、状態に基づいてフォーム要素のスタイルを設定するために使用されます。たとえば、 input:disabled { opacity: 0.5; } は、無効になっている入力フィールドのスタイルを半分の不透明度で設定します。

短いコード例

  • 動的擬似クラス : a:focus { アウトライン: なし; } をクリックすると、リンクをクリックするか、キーボードで移動すると、リンクからフォーカスのアウトラインが削除されます。

  • 動的擬似クラス : button:active {background-color: red; } は、クリックされるとボタンの背景色を赤に変更します。

  • 構造擬似クラス : li:last-child { color: red; } は、すべてのリストの最後のリスト項目を赤く色付けします。

  • 構造擬似クラス : p:nth-child(2) { color: blue; } は、親要素内の 2 番目の段落を選択し、テキストを青色に色付けします。

  • 否定擬似クラス : p:not(.no-border) { border: 1px ソリッドブラック; } は、「no-border」クラスを持たないすべての段落に境界線を追加します。

  • 否定擬似クラス : div:not(#exclude) { border: 1px 実線緑色; } は、ID「exclude」を持たないすべての div 要素に境界線を追加します。

  • 入力疑似クラス : input:checked { 背景色: 緑; } は、チェックされた入力要素の背景色を緑色に変更します。

  • 入力疑似クラス : input:valid { border: 2px 実線緑色; } は、検証ルールに基づいて、すべての有効な入力フィールドに緑色の境界線を追加します。

擬似クラス要素

擬似要素セレクターを使用すると、ドキュメントの特定の部分のスタイルを設定できます。これらは、要素の最初の文字または行のスタイルを設定したり、HTML 要素の前後にコンテンツを挿入したりするために利用できます。

擬似要素の前後

これらの疑似要素を使用すると、要素のコンテンツの前後にコンテンツを挿入できます。

例:

p::before { 
content: "Read this - "; 
color: red;
}
ログイン後にコピー

これにより、各段落のコンテンツの前に「Read this -」が挿入され、赤く色付けされます。

最初の文字と最初の行の擬似要素

これらの疑似要素は、テキスト ブロックの最初の文字または最初の行のスタイルを設定するために使用されます。

例:

p::first-letter { 
font-size: 20px; 
color: blue;
}
ログイン後にコピー

これにより、各段落の最初の文字のサイズが 20 ピクセル、色が青になります。

短いコーディング例

  1. p::after { content: "*"; } - これにより、各段落の後にアスタリスク (*) が追加されます。

  2. .warning::before { content: "警告: ";フォントの太さ: 太字;色: 赤; } - これにより、クラス「warning」を持つ要素のコンテンツの前に「WARNING:」が追加されます。テキストは太字で赤色になります。

  3. blockquote::first-line { font-weight: 太字; } - これにより、すべてのブロック引用符の最初の行が太字になります。

  4. div::first-letter { text-transform: 大文字; } - これにより、すべての div の最初の文字が大文字に変換されます。

  5. h1::after {コンテンツ: "";色: 緑; } - これにより、各 h1 要素の後に緑色のチェック マークが追加されます。

コードペンの例

擬似要素と擬似クラスは私のお気に入りのセレクターのいくつかです。これらを本当に理解するには、たくさん練習することをお勧めします。

ここでは、実験できる Codepen の例をいくつか示します。

例 1

チュートリアル

例 2

チュートリアル

例 3

チュートリアル

これらの例は単純に見えますが、コードをチェックすると、非常に少数の疑似クラスで作成されていることがわかります。

コンビネータセレクター

CSS のコンビネータ セレクターは、他の要素との特定の関係基準を満たす特定の要素を選択する強力な方法です。これらのセレクターを使用すると、要素が別の要素の子、子孫、兄弟であるかどうかなど、ドキュメント ツリー内の関係に基づいて要素をターゲットにすることができます。

子孫コンビネータ

子孫コンビネータはスペースで表されます。特定の要素の子孫である要素を選択します。

例:

div p { color: blue;}
ログイン後にコピー

これにより、すべての

が選択されます。

の子孫である要素要素を選択し、テキストを青色に色付けします。

div p { background-color: yellow;}
ログイン後にコピー

これにより、すべての

が選択されます。

の子孫である要素要素を追加し、背景を黄色にします。

子コンビネータ

子コンビネータは>で表されます。特定の要素の直接の子である要素を選択します。

例:

div > p { color: blue;}
ログイン後にコピー

これにより、すべての

が選択されます。

の直接の子である要素要素を選択し、テキストを青色に色付けします。

div > p { border: 1px solid red;}
ログイン後にコピー

This will select all

elements that are direct children of a

element, and give them a border.

Adjacent Sibling Combinators

An adjacent sibling combinator is denoted by +. It selects an element that is directly after another specific element.

Example:

div + p { color: blue;}
ログイン後にコピー

This will select any

element that is directly after a

element, and color the text blue.

General Sibling Combinators

A general sibling combinator is denoted by ~. It selects elements that are siblings of a certain element.

Example:

div ~ p { color: blue;}
ログイン後にコピー

This will select all

elements that are siblings of a

element, and color the text blue.

Advanced CSS3 Selectors

Advanced CSS3 selectors provide more precise targeting capabilities than basic selectors. These include attribute selectors with various matchers and nth-child/nth-of-type selectors.

Attribute Selectors with Various Matchers

Attribute selectors can be used with various matchers to select elements based on specific conditions related to their attributes.

Example:

input[type="text"] { 
color: blue;
}
ログイン後にコピー

This will select all input elements with the type attribute of "text" and color the text blue.

Nth-child and Nth-of-type Selectors

The nth-child and nth-of-type selectors are used to select elements based on their position in the parent element.

Example:

p:nth-child(2) { 
color: red;
}
ログイン後にコピー

This will select the second child paragraph of its parent element and color the text red.

Short Coding Examples

  1. Attribute Selector with Matcher: a[href^="https"] {font-style: italic;} - This will select all links that have an href attribute that starts with "https" and make the text italic.

  2. Attribute Selector with Matcher: input[type$="text"] {background-color: yellow;} - This will select all input elements that have a type attribute that ends with "text" and give them a yellow background.

  3. Nth-child Selector: li:nth-child(odd) {background-color: grey;} - This will select all odd-numbered list items and give them a grey background.

  4. Nth-of-type Selector: p:nth-of-type(3n) {font-weight: bold;} - This will select every third paragraph and make the text bold.

Best Practices for Using CSS3 Selectors

  1. Use the Right Selector : The key to using CSS3 selectors effectively is to use the right selector for the job. For instance, use class selectors when you want to style a group of elements and ID selectors for unique elements.

  2. Avoid Over-Specification : Over-specifying selectors can make your CSS hard to maintain. Stick to simple selectors as much as possible.

  3. Use Shorthand Properties : Shorthand properties can make your CSS cleaner and easier to read. For example, use margin: 0 auto; instead of margin-top: 0; margin-right: auto; margin-bottom: 0; margin-left: auto;.

  4. Group Selectors : If multiple selectors share the same style declaration, group them together to keep your CSS DRY (Don't Repeat Yourself).

  5. Comment Your Code : Commenting your CSS can help you and others understand what your code does, especially when using complex selectors.

  6. Use Pseudo-classes and Pseudo-elements : These can help you target elements based on their state or position in the document, which can make your CSS more dynamic and responsive.

  7. Keep Specificity Low : Overly specific selectors can lead to specificity wars, making it hard to override styles later. Keep your specificity as low as possible.

  8. Test Across Different Browsers : Different browsers can interpret CSS selectors differently. Always test your CSS across different browsers to ensure consistency.

Conclusion

In conclusion, selectors, ranging from basic type, class, and ID selectors to advanced pseudo-classes, pseudo-elements, and combinators, provide a powerful toolset for styling HTML elements. By understanding and applying these selectors, you can create dynamic, responsive, and aesthetically pleasing websites.

However, it's important to follow best practices such as using the right selector for the job, avoiding over-specification, grouping selectors, and testing across different browsers to ensure the maintainability and consistency of your CSS code.


? Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

?この記事が気に入ったら、共有することを検討してください。

? すべてのリンク | X | LinkedIn

以上がCSSelectors をマスターする: 例を含む完全ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!