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?
source to share
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>
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)
source to share
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.
source to share