<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .box{ width: 200px; height: 200px; border: 1px solid #000000; } .cont{ padding: 50px; background: red; } /*方法1 * 最简单的flex布局,外层容器加上如下样式即可 * display: flex; justify-content: center; align-items: center; * * 兼容性: IE:ie9以上加-ms-前缀 移动端:安卓4.2-4.3加-webkit-前缀 UC浏览器加-webkit-前缀*/ .box1{ display: -webkit-flex; display: -moz-flex; display: -o-flex; display: -ms-flex; display: flex; justify-content: center; align-items: center; } /*方法2 利用table-cell 兼容性ie7以上支持 * */ .box2{ display: table-cell; text-align: center; vertical-align: middle; } .cont2{ vertical-align: middle; display: inline-block; *display:inline; *zoom:1; } /*方法3 使用CSS3 transform 兼容性 IE:ie8以上,ie9加-ms-前缀 安卓4.3-4.4.4版本浏览器加-webkit-前缀 UC加-webkit-前缀 * */ .box3{ position: relative; } .cont3{ position: absolute; left: 50%; top: 50%; transform:translate(-50%,-50%); -ms-transform:translate(-50%,-50%); /* IE 9 */ -moz-transform:translate(-50%,-50%); /* Firefox */ -webkit-transform:translate(-50%,-50%); /* Safari 和 Chrome */ -o-transform:translate(-50%,-50%); /* Opera */ } /*方法4js实现 兼容所有浏览器*/ .box4{ position: relative; } .cont4{ position: absolute; left: 50%; top: 50%; border: 5px solid #000000; } </style> </head> <body> <!--方法1--> <div class="box1 box"> <div class="cont1 cont">1</div> </div> <!--方法2--> <div class="box2 box"> <div class="cont2 cont">2</div> </div> <!--方法3--> <div class="box3 box"> <div class="cont3 cont">3</div> </div> <!--方法4--> <div class="box4 box" id="box4"> <div class="cont4 cont" id="cont4">4</div> </div> <script type="text/javascript"> var cont4=document.getElementById("cont4"); // console.log(cont4.offsetHeight,cont4.clientHeight); linCenter(cont4); function linCenter(obj){ obj.style.marginLeft="-"+obj.offsetWidth/2+"px"; obj.style.marginTop="-"+obj.offsetHeight/2+"px"; } </script> </body> </html>
时间: 2024-11-08 15:43:00