利用CSS的Sass预处理器(框架)来制作居中效果

2020-05-08 09:53:59易采站长站整理

/// 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%;   
}  

在这里让我们暂停一下,深入分析后续逻辑的层次:

widthheightsolution
nullnulltranslate
defineddefinedmargin
definednullmargin-left + translateY
nulldefinedmargin-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`