Generating CSS Rules Using Class Prefixes

Twitter Bootstrap Different Column Selectors have different CSS properties. Col-md-1 has a smaller width than col-md-2. However, they all have common properties.

How do I create one rule that applies to multiple classes, all of which have the same prefix?

I imagine something like this:

.col*{
margin:0,2%;
}
.col-md-1{
width:4.3333333333%;
}
.col-md-2{
width:6.33333333%;
}

      

In the example above, both .col-md-1 and .col-md-2 will have 0.2% margin. What is the correct way (if any) to do this?

+3


source to share


2 answers


You can use:

[class^=col] {margin:0.2%;}

      



div {
  height: 50px;
  margin: 10px;
}
[class^=col] {
  background: red;
}
      

<div class="col-md-1"></div>
<div></div>
<div class="col-md-2"></div>
      

Run codeHide result


This ^=

means "begins with". You can also use [class*=col]

or [class*=md]

for more information, see the specs in matching matching selectors .

(Note that you must use a period instead of a comma or space in your margin declaration)

+4


source


You can either use operator ^=

(starts with) or operator |=

(is in a dash-separated list):

[class^=col] {
    /* this will work just for prefixes */
}

[class|=col] {
    /* this will work for any dash-separated segment... */
}

[class|=md] {
    /* ...such as "md" in your case */
}

      



A word of warning, however, are not the best selectors from a performance standpoint. Try not to use them extensively.

+2


source







All Articles