CSS: advanced attribute selectors example

In this post I'm going to show you some practical examples of advanced CSS 2.1 attribute selectors. More specifically, the selectors in question are (1) the exact match attribute selector, (2) the partial match attribute selector in a dash-separated list of values and (3) the partial match attribute selector in the context of a space-separated list of values. For "values" I mean the values of the various HTML attributes that we're going to test, usually in the form attr="value(s)". To start with, let's sketch a basic HTML structure to stylize first.

<div id="container-main">
    <div id="main">Test</div>
    <div id="secondary" class="secondary box">Test</div>

The selectors we'll use are summarized below.

Advanced CSS 2.1 attribute selectors
Pattern Matches Meaning
div[id|="container"] <div id="container-main"> The first value inside a dash-separated list of values.
div[id="main"] <div id="main"> The exact value of the attribute.
div[class~="box"] <div id="secondary" class="secondary box">Test</div> A value in a space-separated list of values.

The CSS code:

div[id|="container"] {
    width: 400px;
    margin: 2em auto;
    height: 100px;
    border: thick solid teal;

div[id="main"] {
    float: left;
    width: 200px;
    height: 100%;
    background: orange;

div[class~="box"] {
    float: right;
    width: 150px;
    height: 100%;
    background: maroon;
    color: white;


Live example

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.