How to style bootstrap col-lg-* classes?

2020-06-04 03:22发布

问题:

I'm beginner in Less. I want to write a string like "Column-div" in any div with col-lg-[anyNumber] or col-md-[anyNumber] class.

For example something like this code:

.col-lg-*:before {
  content: "Column-div";
  color: #28a4c9;
}

How can I do this with Less?

回答1:

With Less:

One of the options would be to basically create a Less loop like in the below code sample. However, the problem is that the number is fixed and so it would (a) statically generate as many classes as the number (which means bloated code) and (b) if class has a higher suffix value, it won't be covered.

.loop(@count) when (@count > 0){ // execute the function only when condition matches.
  .loop(@count - 1); // call the iteration again with a decremented count
  .col-lg-@{count}:before { // using selector interpolation to add the count number
    content: "Column-div";
    color: #28a4c9;
    }
}

.loop(100); // call the loop with the no. of iterations as the parameter

Codepen Demo


With pure CSS:

There is also a pure CSS alternate for this kind of pattern matching. You can make use of any one of the CSS3 Attribute Selectors depending on your needs. A few samples are available in the snippet.

[class^='col-lg']:before { /* class name starts with col-lg */
  content: "Column-div";
  color: yellow;
}
[class$='col-lg']:before { /* class name ends with col-lg */
  content: "Column-div2";
  color: beige;
}
[class*='col-lg']:before { /* contains col-lg in class name */
  background: chocolate;
}

/* Just for demo */

div:before{
  display: block;
}
<div class='col-lg-1'></div>
<div class='col-lg-2'></div>
<div class='col-lg-3'></div>

<div class='a-col-lg'></div>
<div class='b-col-lg'></div>
<div class='c-col-lg'></div>