问题
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