本文整理一些利用css實現水平置中/垂直置中的一些方法,教程都很基礎,希望對大家有協助!
一、水平置中
1. text-align:center(行內元素)
給其父元素設定屬性 text-align:center;
2. margin: 0 auto(區塊層級元素)
給元素本身設定 margin: 0 auto;
3. 元素的寬度固定
️ position+margin-left
.ele{ position:absolute; width:固定; left:50%; margin-left:-0.5寬度;}
️ position+left:0;right:0;margin:0 auto
.ele{ position:absolute; width:固定; left:0; right:0; margin:0 auto;}
4.元素的寬度不固定
️css3-transform
.ele{ position:absolute; left:50%; transform:translate(-50%,0);}
️css3-width:fit-content(當需要置中的元素設定了float:left時,可以給該元素的父元素設定如下屬性)
.ele-parent{ width: -moz-fit-content; width: -webkit-fit-content; width:fit-content; margin:0 auto;}
該屬性目前只支援Chrome 和 Firefox瀏覽器.
️flex
.ele-parent{ display: flex; justify-content: center;}
二、垂直置中
1. line-height:eleparent-height
單行文本的垂直置中可以設定屬性 line-height:父元素height
2. 元素的高度固定
️position+margin-top
.ele-parent{ position:relative;}.ele{ position:absolute; top:50%; height:固定; margin-top:-0.5高度;}
️ position+top:0;bottom:0;margin:auto 0
.ele{ position:absolute; height:固定; top:0; bottom:0; margin:auto 0;}
3.元素高度不固定
️vertical-align
.ele-parent{ display:table;}.ele{ display:table-cell;
vertical-align:middle;}
️css3-transform
.ele{ position:absolute; top:50%; transform: translate(0,-50%);}
️flex
.ele-parent{ display: flex; align-items:center;}
暫時只整理到這些,不足之處還請 批評指正!!!