一般用于页面弹框的布局
1 <div class="bodybox"> 2 <div class="centerBox"></div> 3 </div>
方法一:使用定位left,right,top,bottom都为0,margin: auto;
1 html, body { 2 height: 100%; 3 } 4 .bodybox{ 5 position: relative; 6 width: 100%; 7 height: 100%; 8 background-color: #ccc; 9 } 10 .centerBox{ 11 position: absolute; 12 width: 200px; 13 height: 200px; 14 left: 0; 15 top: 0; 16 right: 0; 17 bottom: 0; 18 margin: auto; 19 background-color: #f60 20 }
方法二:使用绝对定位,left,top等于50%,margin等于自身-50%
1 html, body { 2 height: 100%; 3 } 4 .bodybox{ 5 position: relative; 6 width: 100%; 7 height: 100%; 8 background-color: #ccc; 9 } 10 .centerBox{ 11 position: absolute; 12 width: 200px; 13 height: 200px; 14 left: 50%; 15 top: 50%; 16 margin-top: -100px; 17 margin-left: -100px; 18 background-color: #f60 19 }
使用计算属性calc(50% - 自身宽度的一半)
1 html, body { 2 height: 100%; 3 } 4 .bodybox{ 5 position: relative; 6 width: 100%; 7 height: 100%; 8 background-color: #ccc; 9 } 10 .centerBox{ 11 position: absolute; 12 width: 200px; 13 height: 200px; 14 left: calc(50% - 100px); 15 top: calc(50% - 100px); 16 background-color: #f60 17 }
使用transform:进行偏移
1 html, body { 2 height: 100%; 3 } 4 .bodybox{ 5 position: relative; 6 width: 100%; 7 height: 100%; 8 background-color: #ccc; 9 } 10 .centerBox{ 11 position: absolute; 12 width: 200px; 13 height: 200px; 14 left: 50%; 15 top: 50%; 16 transform: translate(-50%, -50%); 17 background-color: #f60 18 }
原文:https://www.cnblogs.com/shiyujian/p/14841030.html