Se c'è una scorciatoia CSS drammaticamente manca, è quello che permette di definire la position
proprietà, così come le quattro proprietà di offset ( top
, right
, bottom
, left
).
Fortunatamente, questo è in genere qualcosa che può essere risolto con un preprocessore CSS come Sass. Dobbiamo solo creare un semplice mixin per salvarci dalla dichiarazione manuale delle 5 proprietà.
/// 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; )
Ora il fatto è che ci basiamo su argomenti con nome quando si usa questo mixin per evitare di doverli impostare tutti quando si desidera solo uno o due. Considera il codice seguente:
.foo ( @include position(absolute, $top: 1em, $left: 50%); )
... che si compila in:
.foo ( position: absolute; top: 1em; left: 50%; )
In effetti, Sass non restituisce mai una proprietà che ha un valore di null
.
Semplificare l'API
Potremmo spostare il tipo di posizione nel nome del mixin invece di doverlo definire come primo argomento. Per farlo, abbiamo bisogno di tre mixin extra che serviranno come alias per il mixin `position` che abbiamo appena definito.
/// 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… ); )
Riscrittura del nostro esempio precedente:
.foo ( @include absolute($top: 1em, $left: 50%); )
Andare avanti
Se vuoi una sintassi più vicina a quella proposta da Nib (il framework Stylus), ti consiglio di dare un'occhiata a questo articolo.
.foo ( @include absolute(top 1em left 50%); )