1.绝对定位
不确定当前div的宽度和高度,采用 transform: translate(-50%,-50%);当前div的父级添加相对定位(position: relative;)
#box1{ width: 600px; height: 600px; border: 1px solid blue; position: relative; } .box1{ width: 300px; /*此值可以随意改变 */ height: 300px;/*此值可以随意改变 */ background: red; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%) }
<div id="box1"> <div class="box1"></div> </div>
2.绝对定位
确定当前div的宽度和高度,margin值为当前div的一半
<style> #box2{ width: 600px; height: 600px; border: 1px solid yellow; position: relative; } .box2{ width: 300px; height: 300px; background: red; position: absolute; top: 50%; left: 50%; margin-left: -150px; margin-top: -150px; } </style>
<div id="box2"> <div class="box2"></div> </div>
#box3{ width: 600px; height: 600px; border: 1px solid yellow; position: relative; } .box3{ width: 300px; height: 300px; background: red; position: absolute; top: 0; left: 0; bottom: 0; right: 0; margin: auto; }
<div id="box3"> <div class="box3"></div> </div>
4.flex布局
#box4{ width: 600px; height: 600px; border: 1px solid yellow; display:flex; -webkit-display:flex; align-items:center; -webkit-align-items:center; -webkit-justify-content:center; justify-content:center; } .box4{ width: 300px; height: 300px; background: red; }
<div id="box4"> <div class="box4"> </div> </div>
5.table-cell实现水平垂直居中: table-cell middle center组合使用
< div class="table-cell"> < p >你</ p > </ div > |
1
|
/**css**/ |
1
2
3
4
5
6
7
8
|
.table-cell { display: table-cell; vertical-align: middle; text-align: center; 240px; height: 180px; border:1px solid #666; } |
6.calc()