csscss-selectors

How to get element by its partial class name with CSS?


I am creating few CSS buttons and would like to style them as short as possible so I started like this:

[class*='mybuttons-button']{
    margin-top:5px;
    -webkit-border-radius:4px;
    -khtml-border-radius:4px;
    -moz-border-radius:4px;
    border-radius:4px;
    display:inline-block;
    padding:6px 12px;
    color:#fff;
    vertical-align:middle;
    cursor:pointer;
}

Which will affect all elements that contain class my-button.

Now I want to get deep in to it and do this:

[class*='-large']{
    padding: 10px 16px;
    font-size:120%;
    line-height: 1.33;
    -webkit-border-radius:6px;
    -khtml-border-radius:6px;
    -moz-border-radius:6px;
    border-radius:6px;
}
[class*='mybuttons-button-color']{
    background:blue;
}

But since the class -large might come up in some 3rd party CSS added by user I would like to be more specific and say something like this instead:

[class*='mybuttons-button-*ANYTHING*-large']

So that I don't have to do this:

mybuttons-button-color-large
mybuttons-button-red-large
mybuttons-button-green-large
mybuttons-button-color-medium
mybuttons-button-red-medium
mybuttons-button-green-medium

Does anyone know a way to do this? Is it possible at all, to nail the middle word instead contains only?

I know I can space the class names etc , but would love to give this a try since, to me, this:

<span class="mybuttons-button-color-large"></span>

Looks cleaner than this:

<span class="mybuttons-button color large"></span>

Solution

  • In the same way you can do this .class.class2.class3 { /*styles*/ } to target only things that have all 3 classes, you can can combine attribute selectors to do the same:

    [class*="mybuttons-button"][class*="-large"] { /*styles*/ }
    

    Granted it won't work in a case like this:

    <span class="my-buttons-button-color-small something-else-large"></span>
    

    since it contains both mybuttons-button and -large.

    If you didn't think that would happen or be an issue you should be fine. Here's a fiddle: http://jsfiddle.net/3wEJe/

    Definitely wouldn't recommend it though.