简体   繁体   中英

Can I use Less to set a CSS background image based on a class name?

I have a template technology that generates my DOM and less generating my CSS. In my template, I am iterating over a list of objects that include a name for an icon image.

What I would like to do is take that icon image name and use it as a CSS class. Then with less, set the background image path to something based on that class name:

.className {background: url(../some/path/constant/[@className].png);}

..saving from me needing to set the background style in the template itself.

Yes!! Setting CSS background is not dependent on LESS. If you can do it using CSS, then you can always do it by less.

To set different background image (LESS way)

@image-base-url: "http://your-images-url.com";

.className1 {
    background-image: url("@{image-base-url}/image1.png");
 }
.className2 {
    background-image: url("@{image-base-url}/image2.png");
 }
.className3 {
    background-image: url("@{image-base-url}/image3.png");
 }

In your HTML:

<div class="className1>
      <span> This will have image1.png as background</span>
</div>
<div class="className2>
      <span> This will have image2.png as background</span>
</div>
<div class="className3>
      <span> This will have image3.png as background</span>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM