1. 程式人生 > >純CSS實現垂直居中

純CSS實現垂直居中

總結歸納一下現在學到的純CSS實現水平垂直居中的方法:

(1)如果元素的寬度是已知的,那麼可以利用父類元素設定成position:relative,子類設定為position:absolute

然後定位距離上margin為50%,左50%,再減去元素自身的寬度就可以實現,例子程式碼:

<div class = "box">
    <div class="content">CJ</div>
</div>
<style>
.box {
    background-color: gray;
    width: 200px;
    height: 200px;
    position: relative;
}
.content {
    background-color: yellow;
    width: 20px;
    height: 20px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin: -10px 0 0 -10px;
	text-align: center;
	vertical-align: middle;
}
</style>  

實現效果:

(2)div模組絕對定義水平垂直居中,利用margin: auto實現

div{
   width: 100px;
   height: 100px;
   background: red;
   position: absolute;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   margin: auto;
}

(3)div模組絕對定義水平垂直居中,利用margin負邊距實現(常用用法)

div{
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
            left: 50%;
            top: 50%;
            margin-left: -50px;
            margin-top: -50px;
        }

(4)div絕對定位水平垂直居中,利用transform變形(IE8以下版本不支援)

div{
            width:100px;
            height: 100px;
            background:red;
            position: absolute;
            left: 50%;    /* 定位父級的50% */
            top: 50%;
            transform: translate(-50%,-50%); /*自己的50% */
        }

(5)css不定寬高水平垂直居中

<style>
.box{
	     width: 200px;
             height: 200px;
	     background: black;
             display: flex;
             justify-content: center;
             align-items: center;
        }
.content{
            background: green;
            width: 100px;
            height: 100px;
        }
</style>
	<div class = "box">
		<div class = "content"></div>
	</div>
</body>

(6)將父盒子設定為table-cell,就相當於一個td,td是行內元素,無法設定寬高,因此需要巢狀一層,然後必須選擇display:inline-block,因此巢狀蹭會被覆蓋掉,不推薦使用這種方法。

<div class="box">
    <div class="content">
        <div class="inner">
        </div>
    </div>
</div>

.box {
    background-color: #FF8C00;//橘黃色
    width: 300px;
    height: 300px;
    display: table;
}
.content {
    background-color: #F00;//紅色
    display: table-cell;
    vertical-align: middle;//使子元素垂直居中
    text-align: center;//使子元素水平居中
}
.inner {
    background-color: #000;//黑色
    display: inline-block;
    width: 20%;
    height: 20%;
}

(7)flex佈局:利用子類設定margin:0 auto,以及父類設定display:flex;align-items:center實現子類垂直水平居中

.box{
    width: -moz-fit-content;
    width: -webkit-fit-content;
    background-color:red;
    width:300px;
    height:300px;
    display: flex;
    align-items: center;
}
.content{
	margin:0 auto;
	width:50%;
	height:50%;
	background: green;
	}