知道元素的宽高
1.absoult +magin auto
.parent{ /*父元素为除了static以外的定位方式*/ position: relative; width: 500px; height: 500px; border: 1px solid red;}.child{ /*子元素为绝对定位*/ position: absolute; width: 200px; height: 200px; /*top、bottom、left和right 均设置为0*/ top: 0; bottom: 0; left: 0; right: 0; /*margin设置为auto*/ margin:auto; border: 1px solid green; }
2.absoult +负magin
.parent{ position: relative; width: 500px; height: 500px; border: 1px solid red;}.child{ position: absolute; width: 200px; height: 200px; top: 0; left: 0; margin-left: -100px; margin-top: -100px; border: 1px solid green; }
3、.absoult + calc
.parent{ position: relative; width: 500px; height: 500px; border: 1px solid red;}.child{ position: absolute; width: 200px; height: 200px; top: calc(50% - 100px); left: calc(50% - 100px); border: 1px solid green; }
不知道元素的宽高
1.webkit-box
//对父级元素设置position: relative;display: -webkit-box;-webkit-box-align: center;-webkit-box-pack: center;
2.css —tabe
.parent { width: 500px; height: 500px; border: 1px solid red; display: table-cell; vertical-align: middle; //实现垂直居中 text-align: center;}.child { display:inline-block;}
3.flex
.parent{ display:flex; justify-content:center; align-items:center;}
4.absolute+transform
<div class="parent"> <div class="child">Demo</div></div><style> .parent { position: relative; } .child { position: absoult; left: 50%; top: 50%; transform: translate(-50%, -50%); //偏移自身的宽和高的-50% }</style>