1、利用伪类实现垂直居中(居中元素大小可未知)
<style> .main{300px;height:300px;border:1px solid;} .center{100px;height:100px;border: 1px solid;display: inline-block;vertical-align: middle;} .main:after{display:inline-block; 0; height:100%; content:"center"; vertical-align:middle; overflow:hidden;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>
要点:居中元素需要是 display:inline-block;属性的元素。
2、利用transform:translate(),实现垂直居中(居中元素大小可未知)
<style> .main{300px;height:300px;border:1px solid;} .center{100px;height:100px;border: 1px solid;} .center{position:relative;transform: translateY(-50%);top:50%;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>
原理:居中元素需要是定位,通过负自身的50%来实现居中。
3、利用flex实现垂直居中(居中元素大小可未知)
<style> .main{300px;height:300px;border:1px solid;} .center{100px;height:100px;border: 1px solid;} .main{display: -webkit-box;display: -ms-flexbox;-webkit-display:flex;display: flex;align-items: center;-webkit-align-items:center;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>
要点:align-items:center; (适用于父盒子上,用于设置垂直对齐方式)
4、position方法实现居中(居中元素大小可未知)
<style> .main{300px;height:300px;border:1px solid;position:relative;} .center{100px;height:100px;border: 1px solid;} .center{position:absolute;top:0;bottom:0;left:0;right:0;margin:auto;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>
要点:top和bottom都要设为0;
5、常用方法position(居中元素大小需已知)
<style> .main{300px;height:300px;border:1px solid;} .center{100px;height:100px;border: 1px solid;} .center{position:relative;top:50%;margin-top:-50px;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>
要点:position以后,margin-top负50%盒子都高度;
6、table-cell
<style> .main{300px;height:300px;border:1px solid;} .center{100px;height:100px;border: 1px solid;display: table;} .main{display: table-cell;vertical-align: middle;} </style> </head> <body> <div class="main"> <div class="center"></div> </div> </body>