Attribute Value selectors
Lesson 13 of 15 in Coddy's CSS Selectors course.
In this lesson, you will delve into the concept of attribute value starting with selectors. This technique allows you to target HTML elements based on the initial characters of their attribute values.
Attribute Value Starting With Selector Syntax:
To target elements with attribute values that start with a specific string, use the [attribute^="value"] selector syntax.
Code Examples:
HTML:
<button class="btn-primary">Primary Button</button>
<button class="btn-secondary">Secondary Button</button>
<button class="btn-tertiary">Tertiary Button</button>CSS:
/* Selects buttons with class attribute values starting with "btn-" */
[class^="btn-"] {
background-color: lightgray;
}In the provided code examples:
- Three buttons are defined with different class attribute values.
- The CSS rule
[class^="btn-"]targets elements with aclassattribute value that starts with "btn-". It applies thebackground-color: lightgray;style to these buttons.
The result is that all three buttons will have a light gray background color, as their class attribute values start with "btn-".
Challenge
EasyImagine you have the following HTML structure for a list of items. Your goal is to style list items with a specific data-category attribute value that starts with "fruit-". Apply a unique background color to these list items using CSS.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Attribute Value Starting With Selector</title>
<style>
/* Your CSS code here */
</style>
</head>
<body>
<ul>
<li data-category="fruit-apple">Apple</li>
<li data-category="vegetable-carrot">Carrot</li>
<li data-category="fruit-banana">Banana</li>
<li data-category="fruit-orange">Orange</li>
<li data-category="grain-rice">Rice</li>
</ul>
</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