Menu
Coddy logo textTech

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 a class attribute value that starts with "btn-". It applies the background-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 icon

Challenge

Easy

Imagine 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