I've created a Mixin in Less CSS. It can do the following things:
- Set the position-rule of an element.
- Place the element in one of the corners (e.g. top left, bottom right etc.)
- Alternatively it can set explicit values for
top|right|bottom|left
.
Usage example:
.test-1 {
.position(absolute, top, right);
}
Examples showing the resulting CSS:
.position() { position: static; }
.position(relative) { position: relative; }
.position(absolute, top, right) { position: absolute; top: 0; bottom: auto; left: auto; right: 0; }
.position(absolute, bottom, left) { position: absolute; top: auto; bottom: 0; left: 0; right: auto; }
.position(fixed, 20px, 50%) { position: fixed; top: 20px; right: 50%; }
.position(fixed, 10px, null, null, 10%) { fixed: absolute; top: 10px; left: 10%; }
.position(absolute, 10px, -, -, 10%) { position: absolute; top: 10px; left: 10%; }
The Mixin:
.position(@position: static; @a: null; @b: null; @c: null; @d: null) {
position: @position;
& when (top = @a) {
top: 0;
bottom: auto;
}
& when (bottom = @a) {
top: auto;
bottom: 0;
}
& when (left = @b) {
left: 0;
right: auto;
}
& when (right = @b) {
left: auto;
right: 0;
}
& when not (null = @a) and not (~'-' = @a) and not (top = @a) and not (bottom = @a) {
top: @a;
}
& when not (null = @b) and not (~'-' = @b) and not (top = @b) and not (bottom = @b) {
right: @b;
}
& when not (null = @c) and not (~'-' = @c) {
bottom: @c;
}
& when not (null = @d) and not (~'-' = @d) {
left: @d;
}
}
I've also created a shortahand version .p()
, which can be called instead of .position()
:
.p(@position: static; @a: null; @b: null; @c: null; @d: null) {
.position(@position; @a; @b; @c; @d);
}
My questions are:
- Is this a useful Mixin?
- Or is it a bad practie to create Mixins like this?
- Is it too complicated or too hard to understand?
- Can this be optimized or shortend?
Even though most of the time I need to use top
and left
for positioning, I found it more related to other CSS rules like margin
when the values are sorted clockwise like top|right|bottom|left
.