CSS Attribute Selectors šŸŽÆ

beginner
11 min

CSS Attribute Selectors šŸŽÆ

Welcome back to CodeYourCraft! Today, we're diving into the world of CSS Attribute Selectors. These are powerful tools that allow you to style HTML elements based on their attributes. Let's get started! šŸ“

What are CSS Attribute Selectors?

Imagine you want to style all <a> tags that have the href attribute pointing to a PDF file. CSS Attribute Selectors make this possible! They help you select HTML elements based on the attributes they possess.

Basic Attribute Selectors

The [attribute] Selector

This selector matches elements that have the specified attribute, regardless of its value.

html
<a href="example.html">Link 1</a> <a href="example.pdf">Link 2</a>
css
a[href] { color: blue; }

šŸ’” Pro Tip: The above CSS rule will color all <a> tags, regardless of the href value.

The [attribute=value] Selector

This selector matches elements that have the specified attribute with the exact value.

html
<a href="example.html">Link 1</a> <a href="example.pdf">Link 2</a>
css
a[href="example.html"] { color: red; }

šŸ’” Pro Tip: The above CSS rule will color only the first <a> tag, as it's the one with the href value "example.html".

Advanced Attribute Selectors

The [attribute~=value] Selector

This selector matches elements that have the specified attribute with a value containing the exact word (separated by whitespace).

html
<a href="example-1.html">Link 1</a> <a href="example-2.pdf">Link 2</a> <a href="example-3.jpg">Link 3</a>
css
a[href~="example"] { color: green; }

šŸ’” Pro Tip: The above CSS rule will color all links that contain "example" in their href value.

The [attribute^=value] Selector

This selector matches elements that have the specified attribute with a value starting with the exact word.

html
<a href="example-1.html">Link 1</a> <a href="example-2.pdf">Link 2</a> <a href="example-3.jpg">Link 3</a>
css
a[href^="example"] { color: orange; }

šŸ’” Pro Tip: The above CSS rule will color all links that start with "example" in their href value.

The [attribute$=value] Selector

This selector matches elements that have the specified attribute with a value ending with the exact word.

html
<a href="example-1.html">Link 1</a> <a href="example-2.pdf">Link 2</a> <a href="example-3.jpg">Link 3</a>
css
a[href$=".html"] { color: purple; }

šŸ’” Pro Tip: The above CSS rule will color only the first <a> tag, as it's the one with the href value ending with .html.

Practice Time! šŸ“

Quick Quiz
Question 1 of 1

Which CSS Attribute Selector do you use to select elements with the exact value in their attribute?

That's it for today! In the next lesson, we'll dive deeper into CSS to learn more powerful selectors and techniques. Happy coding! āœ