总结一下几种在网页中常用的居中方法
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <style> /* .center{ display: flex; justify-content: center; //弹性盒子模型居中 } */ /* .center{ width: 200px; text-align: center; margin: 0 auto; //水平居中 } */ /* .center{ position: absolute; width: 200px; height: 200px; text-align: center; left: 50%; top: 50%; margin-left: -100px; //水平居中 margin-top: -100px; //垂直居中 } */ .center{ position: absolute; left: 50%; top: 50%; /* translate(-50%,-50%) 作用是,往上(x轴),左(y轴)移动自身长宽的 50%,以使其居于中心位置 */ transform: translate(-50%, -50%); //水平加垂直居中 } /* .center{ height: 200px; text-align: center; //文本水平居中 line-height: 200px; //设置行高,垂直居中 } */ /* .center{ width: 200px; text-align: center; height: 20px; line-height: 20px; position: absolute; top: 0; bottom: 0; right: 0; left: 0; margin: auto; } */ </style> </head> <body> <div class="center">我居中了!</div> </body> </html>
说一下我对最后一种的理解吧,top:0 left:0 right:0 bottom:0,实际上是做不到的,其中top和left特别强势,好像4个人拉着绳子拉着这个盒子,但是margin: atuo,它就像一个公平的裁判,让4个人平均的拉,于是就出现了居中的情况,也不懂我这样理解对不对,如有不对,还请大佬指正
我觉得第二种和第三种还是用的比较多
当然还有很多其他的,以后继续补充吧
加一个。
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
这样不能居中啊