Search code examples
csscss-selectorsbem

Why doesn't css selector - 'begins with' allow double-dash at end?


In writing CSS I use BEM methodology and I've found using the CSS selector 'begins with' - [class^="classname"] very useful. This is especially true when declaring styles for modifiers, i.e. .block__element--modifier.

Therefore when writing CSS rules I would like to use [class^="block__element--"] to target specific elements regardless of their modifier. However, I've noticed the double-dash at the end of the selector fails to target the elements. A single dash however will work.

I've had a look through the CSS Selectors Level 3 spec but cannot see any mention of why the double-dash would fail.


Solution

  • I don't think that should cause you any problem as I just tested with the markup below and it works well...

    <div class="block__element--modifier">Hello</div>
    
    div[class^="block__element--"] {
        color: red;
    }
    

    Demo

    Also, this ^= means that the class name begins with the above string, failing that will result in failure of your selector as well, you may like to use *= instead which searches for a substring.

    So if you have a class declared before say like

    <div class="hello block__element--modifier">Hello</div>
    

    Will fail your selector Demo, so in this case you may like using

    div[class*="block__element--"] {
        color: red;
    }
    

    Demo 2