Mixin for Offset Positioning

0
0

If there is one shorthand CSS dramatically misses, it is the one making it possible to define the position property, as well as the four offset properties (toprightbottomleft).

Fortunately, this is typically something that can be solved with a CSS preprocessor such as Sass. We only have to build a simple mixin to save us from declaring the 5 properties manually.

/// Shorthand mixin for offset positioning
/// @param {String} $position - Either `relative`, `absolute` or `fixed`
/// @param {Length} $top [null] - Top offset
/// @param {Length} $right [null] - Right offset
/// @param {Length} $bottom [null] - Bottom offset
/// @param {Length} $left [null] - Left offset
@mixin position($position, $top: null, $right: null, $bottom: null, $left: null) {
  position: $position;
  top: $top;
  right: $right;
  bottom: $bottom;
  left: $left;
}

Now the thing is we rely on named arguments when using this mixin to avoid having to set them all when only one or two are desired. Consider the following code:

.foo {
  @include position(absolute, $top: 1em, $left: 50%);
}

… which compiles into:

.foo {
  position: absolute;
  top: 1em;
  left: 50%;
}

Indeed, Sass never outputs a property that has a value of null.

#Simplifying the API

We could move the type of position to the mixin name instead of having to define it as first argument. To do so, we need three extra mixins that will serve as aliases to the `position` mixin we just defined.

/// Shorthand mixin for absolute positioning
/// Serves as an alias for `position(absolute, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin absolute($args...) {
  @include position(absolute, $args...);
}

/// Shorthand mixin for relative positioning
/// Serves as an alias for `position(relative, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin relative($args...) {
  @include position(relative, $args...);
}

/// Shorthand mixin for fixed positioning
/// Serves as an alias for `position(fixed, ...)`
/// @param {Arglist} $args - Offsets
/// @require {mixin} position
@mixin fixed($args...) {
  @include position(fixed, $args...);
}

Rewriting our previous example:

.foo {
  @include absolute($top: 1em, $left: 50%);
}

#Going further

If you want a syntax closer to the one proposed by Nib (Stylus’ framework), I recommend you have a look at this article.

.foo {
  @include absolute(top 1em left 50%);
}
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.