By utilizing pure Less, you have the ability to create a parameterized mixin for panels and easily generate the margin-left
based on the specified input parameter. This method eliminates the need for separate variables and simplifies your code in Less.
Less:
&.settings-prompt .panel {
.panel(330px);
height: 200px;
}
&.create-playlist-prompt .panel {
.panel(130px);
height: 180px;
}
.panel(@width){ /* Updated as per suggestion by seven-phases-max */
margin-left: (@width / -2); /* calculate -50% of width for margin-left */
width: @width; /* set input parameter as width */
}
Compiled Output:
.settings-prompt .panel {
margin-left: -165px;
width: 330px;
height: 200px;
}
.create-playlist-prompt .panel {
margin-left: -65px;
width: 130px;
height: 180px;
}
View Less Demo
Using jQuery: (Providing an alternative solution for future readers)
$("div").each(function() { // automatically assign margin for each div
var el = $(this);
el.css({
'margin-left': -(el.width()/2) //set margin-left to -50% of width (-width/2);
});
});
View jQuery Demo