1.使用絕對定位方法,配合margin負值使用。能夠實現css
<div class="div0"> <div class="div1"> </div> </div> .div0 { width: 80%; height: 500px; background: lightblue; position: relative; margin: 0 auto; } .div1{ width: 200px; height: 150px; background: lightcoral; position: absolute; left: 50%; top:50%; margin-top: -75px; margin-left: -100px; } css3簡化上面的方法 <div class="div0"> <div class="div1"> </div> </div> .div0 { width: 80%; height: 500px; background: lightblue; position: relative; margin: 0 auto; } .div1{ width: 200px; height: 150px; background: lightcoral; position: absolute; left:calc(50% - 75px); top:calc(50% - 100px); }
2.使用height + line-height的方式,設置一樣的值,配合text-align的使用,便可實現文本的水平垂直居中對齊css3
<div class="div0"> 若是是單行文本,行高如塊的高度同樣時將居中,只一行,行高和元素同樣高,居中 </div> .div0 { background: lightblue; height: 80px; line-height:80px; text-align:center; }
<div class="div0"> <div class="div1"></div> </div> .div0{ width:80%; height:90%; border:3px solid lightblue; margin:0 auto; position:relative } .div1{ width:200px; height:150px; background:lightgreen; position:absolute; /*居中開始*/ top:0px; left:0px; right:0px; bottom:0px; margin:auto; /*居中結束*/ }
2.CSS3中有transform屬性,此屬性下有一個translate移動函數,此函數接受兩個參數。若是兩個參數都爲百分比值,此時會基於自身寬度和高定進行移動面試
<div class="div0"> <img src="img.png" class="img1"> </div> .div0 { width: 80%; height: 70%; background: lightblue; margin: 0 auto; position: relative; } .img1 { position: absolute; top: 50%; left: 50%; transform:translate(-50%,-50%); }
3.css3彈性盒子flex,設置水平居中屬性justify-content:center
,設置垂直居中屬性align-item:center
函數
<div class="flex"> <div class="item"> aaa </div> </div> .flex{ width:400px; height:400px; display:flex; align-items:center; justify-content: center; border:1px solid #000; } .flex .item{ width:50px; height:50px; background:red; border:1px solid #000; }
4.使用能夠使用 display: table
來模擬表格,並給子元素設置display: table-cell
,讓其成爲表格的某個單元格,同時設置vertical-align: middle
,便可實現垂直居中佈局佈局
<div class="container"> <div class="inner"> hello world! </div> </div> .container { display: table; /* 讓div以表格的形式渲染 */ width: 100%; border: 1px solid red; } .inner { display: table-cell; /* 讓子元素以表格的單元格形式渲染 */ text-align: center; vertical-align: middle; }
1.`vertical-align:middle這個屬性的特色,它是相對於兄弟級行高(line-height)來定位(個人理解).flex
<div class="div0"> <img src="img.png" class="img1"><span class="span1"></span> </div> .div0 { width: 80%; height: 500px; background: lightblue; position: relative; margin: 0 auto; text-align: center; } .img1{ vertical-align: middle; } .span1{ line-height:500px; }
2.某些時候須要將小圖標與文字對齊,能夠使用對齊的屬性absmiddle(絕對居中)spa
<div class="div1"> <img src="img.png" align="absmiddle">電視機</div> .div1{ border: 2px solid lightblue; }