Reputation: 29331
I have the following LESS:
&.settings-prompt .panel {
margin-left: -190px;
width: 380px;
height: 200px;
}
&.create-playlist-prompt .panel {
margin-left: -165px;
width: 330px;
height: 180px;
}
Essentially, I would always like .panel
's margin-left to be -50% of its width. Is that possible to express with LESS?
Upvotes: 1
Views: 2939
Reputation: 89780
With pure Less you can create a paramterized mixin for the panel and then use it to generate the margin-left
based on the input paramter like below. This doesn't require usage of separate variables but just usage of the mixin instead of assigning width everytime. It also reduces your lines of code in Less.
Less:
&.settings-prompt .panel {
.panel(330px);
height: 200px;
}
&.create-playlist-prompt .panel {
.panel(130px);
height: 180px;
}
.panel(@width){ /* Updated based on comment by seven-phases-max */
margin-left: (@width / -2); /* calculate -50% of width and use as margin-left */
width: @width; /* assign the input param 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;
}
Using jQuery: (Just in case any future reader is looking for this option)
$("div").each(function() { // call function to auto assign margin for every div
var el = $(this);
el.css({
'margin-left': -(el.width()/2) //set margin-left as - 50% (-width/2);
});
});
Upvotes: 3