Calculating background-position with a formula in LESS Css

谁说胖子不能爱 提交于 2019-12-12 09:28:13

问题


I need to be able to calculate the background position using a math formula in LESS Css via a function method that takes the x and y position of a sprite image. My best guess for this is as follows, but alas this doesn't work.

@icon_base: 30px;
@icon: 24px;
/*sets the position of the background based on the x and y position order */
.icon_position(@x: 1, @y: 1) {
    @posx: ((#sizes[@icon_base] - #sizes[@icon])/2 + (@x * #sizes[@icon_base])) * -1;
    @posy: ((#sizes[@icon_base] - #sizes[@icon])/2 + (@y * #sizes[@icon_base])) * -1;
    background-position: @{posx}px @{posy}px;
}

回答1:


I think you have some things in your operation that are not understood by lesscss. I rewrote your operation as so:

@icon_base: 30px;
@icon: 24px;
/*sets the position of the background based on the x and y position order */
.icon_position(@x: 1, @y: 1) {
    @posx:((@icon_base - @icon)/2 + (@x * @icon_base)) * -1;
    @posy:((@icon_base - @icon)/2 + (@y * @icon_base)) * -1;
    background-position:~`"@{posx}"` ~`"@{posy}"`;  
}

It runs without error and by default it outputs:

background-position: -33px -33px;


来源:https://stackoverflow.com/questions/8216001/calculating-background-position-with-a-formula-in-less-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!