CSS居中布局

 

  • 水平居中

    • 行内元素: text-align: center
    • 块级元素: margin: 0 auto
    • relative + transform
    • flex + justify-content: center(考虑兼容性)
  • 垂直居中

    • line-height: height
    • relative + transform
    • flex + align-items: center(考虑兼容性)
  • 水平垂直居中

    • relative + transform
    • relative + top50% left50% + margin自身宽度一半
    • flex + justify-content + align-items(考虑兼容性)

 水平居中   

    常见行内元素: h1 - h6,p,div ,ol ,ul,table ,form 等

    常见块级元素:a,b(粗体),br ,font ,image,input,label ,strong ,textarea 等

 行内元素:

//实现文本居中
p
{ text-align : center; }
//实现div居中,子元素inline-block
.parent{
  text-align:center
}
.son{
 display:inline-block
}
    块级元素:

//上下边距为0 左右边距自动
#center{
     margin : 0 auto;
}

flex实现水平居中(考虑浏览器兼容性):在父元素中设置flex

#center{
    display : flex;
    justify-content: center;  /*水平居中*/        
}

 垂直居中     

flex实现垂直居中(考虑浏览器兼容性):在父元素中设置flex

#center{
    display : flex;
    align-items : center; /*垂直居中*/        
}

line-height实现垂直居中:line-height:height;

水平垂直居中      

 relative + transform实现居中:

#center{
 position : relative;
top : 50%;
left : 50%;
transform : translate(-50%,-50%); /*x,y轴移动父元素的一半*/
//margin : -50px 0 0 -150px; /*可替换
transform 长度为容器宽高的一半*/
}

flex实现水平垂直居中(考虑浏览器兼容性):在父元素中设置flex

#center{
    display : flex;
    justify-content: center;  //水平居中
    align-items : center;    //垂直居中  
}

 

 

 

posted @ 2019-02-18 11:45  张小VV  阅读(171)  评论(0编辑  收藏  举报