Attribute Value selectors III
Lesson 15 of 15 in Coddy's CSS Selectors course.
In this lesson, we'll explore the concept of attribute value containing selectors. This technique allows you to target HTML elements based on whether their attribute values contain a specific substring.
Attribute Value Containing Selector Syntax:
To target elements with attribute values containing a specific string, you use the [attribute*="value"] selector syntax.
Code Examples:
HTML:
<div class="tag fruit">Apple</div>
<div class="tag vegetable">Carrot</div>
<div class="tag fruit">Banana</div>
<div class="tag fruit">Orange</div>
<div class="tag grain">Rice</div>CSS:
/* Selects <div> elements with class attribute values containing "fruit" */
[class*="fruit"] {
color: green;
}Explanation of Code Examples:
In the provided code examples:
- Five
<div>elements are defined with different class attribute values. - The CSS rule
[class*="fruit"]targets elements with aclassattribute value containing the substring "fruit". It applies thecolor: green;style to these elements.
As a result, the <div<strong>></strong> elements with class attributes "tag fruit" will have green text color.
Challenge
EasyYou are tasked with styling a list of products on a webpage. Each product is represented by a <div> element with a data-tags attribute indicating its tags (e.g., "electronics", "clothing", "accessories"). Your goal is to style the products differently based on their tags using attribute value containing selectors.
Your CSS task is to:
- Give unique background color to products with the
data-tagsattribute containing "electronics". - Give unique border to products with the
data-tagsattribute containing "clothing". - Give unique background color to products with the
data-tagsattribute containing "accessories".
Try it yourself
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product List</title>
<style>
/* Your CSS code here */
</style>
</head>
<body>
<div data-tags="electronics">Smartphone</div>
<div data-tags="clothing">T-Shirt</div>
<div data-tags="accessories">Sunglasses</div>
<div data-tags="electronics clothing">Headphones</div>
</body>
</html>
All lessons in CSS Selectors
4Attribute selectors
Intro to Attribute SelectorsPresence and Exact ValuesAttribute Value selectors Attribute Value selectors IIAttribute Value selectors III3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector