简体   繁体   中英

LESS css set dynamic background image with mixin

I am using LESS CSS .

I am currently using Mixins with variables.

Something like this works okay:

.border-radius (@radius) { border-radius: @radius; }

#header { .border-radius(4px);  }

This is :

.bg-img(@img) { background-image:url(@img); }

#logo { .bg-img("../images/logo.jpg"); }

i have tried combinations of using ' & " in the background-image:url but then it tries to get the image as images/@img instead of the image name. other wise it gives me an error of但随后它尝试将图像作为images/@img而不是图像名称。否则它给了我一个的错误
Cannot call method 'charAt' of undefined

I think writing background-image:url() all the time is too tedious, is this possible..?

:) got my answer!

it needs to be used like this in my case:

.bg-img(@img) { background-image:url("@{img}"); }

#logo { .bg-img("../images/logo.jpg"); }

You can further improve on this by adding the first part of the image path to the initial mixin so you only have to write it once:

.bg-img(@img) { background-image:url("../images/@{img}"); }

#logo { .bg-img("logo.jpg"); }

A small improvement but does add a little elegance.

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