0
0
CSSmarkup~3 mins

Why Starts-with and ends-with selectors in CSS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a few simple symbols can save you hours of tedious CSS work!

The Scenario

Imagine you have a long list of product codes on a webpage. You want to highlight all products whose codes start with "A" or end with "Z" by changing their color.

The Problem

If you try to do this manually, you must write separate CSS rules for each exact code or add special classes to each item. This is slow, error-prone, and hard to maintain when new products are added.

The Solution

Starts-with and ends-with selectors let you target elements based on the beginning or ending of attribute values. This means you can write one rule to style all matching items automatically.

Before vs After
Before
li[data-code='A123'] { color: red; }
li[data-code='A456'] { color: red; }
li[data-code='XYZ'] { color: blue; }
After
li[data-code^='A'] { color: red; }
li[data-code$='Z'] { color: blue; }
What It Enables

You can style groups of elements dynamically based on attribute patterns without extra HTML changes.

Real Life Example

On an online store, highlight all items starting with "NEW" to show new arrivals, or all items ending with "-sale" to mark discounted products.

Key Takeaways

Manual styling for many similar items is slow and error-prone.

Starts-with (^=) and ends-with ($=) selectors target attribute values by their start or end.

This makes styling dynamic groups easy and maintainable.