Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating CSS Rules Using Class Prefixes [duplicate]

Twitter Bootstrap's different column selectors have different CSS properties. Col-md-1 has a smaller width than col-md-2. However, they all have some properties in common.

How can one rule be created that applies to multiple classes who all share 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 of .col-md-1 and .col-md-2 would have a margin of 0,2%. What is the correct way (if any) of doing this?

like image 696
Patrick Motard Avatar asked Dec 05 '25 17:12

Patrick Motard


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>

This ^= means "begins with". You could also use the [class*=col] or [class*=md] for more info, see the specs on substring matching attribute selectors.

(Note that you should be using a dot instead of a comma or a white space in the margin value declaration)

like image 67
web-tiki Avatar answered Dec 08 '25 08:12

web-tiki


You can either use a ^= operator (starts with), or a |= operator (is on 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, though - these aren't the best selectors in terms of performance. Try not to use them extensively.

like image 38
Michał Dudak Avatar answered Dec 08 '25 07:12

Michał Dudak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!