/// Horizontal, vertical or absolute centering of element within its parent
/// If specified, this mixin will use negative margins based on element’s
/// dimensions. Else, it will rely on CSS transforms which have a lesser
/// browser support but are more flexible as they are dimension-agnostic.
///
/// @author Hugo Giraudel
///
/// @param {Length | null} $width [null] – Element width
/// @param {Length | null} $height [null] – Element height
///
@mixin center($width: null, $height: null) { .. }
然后,由分析知,要实现居中必须让元素绝对定位:
@mixin center($width: null, $height: null) {
position: absolute;
top: 50%;
left: 50%;
}
在这里让我们暂停一下,深入分析后续逻辑的层次:
| width | height | solution |
|---|---|---|
| null | null | translate |
| defined | defined | margin |
| defined | null | margin-left + translateY |
| null | defined | margin-right + translateX |
秀代码:
CSS Code复制内容到剪贴板
@mixin center($width: null, $height: null) {
position: absolute;
top: 50%;
left: 50%;
@if not $width and not $height {
// Go with `translate`
} @else if $width and $height {
// Go width `margin`
} @else if not $height {
// Go with `margin-left` and `translateY`










