1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style type="text/css"> 7 *{ 8 margin: 0; 9 padding: 0; 10 } 11 .center-vertical{ 12 position:relative; 13 top:50%; 14 transform:translateY(-50%); 15 } 16 #box{ 17 height: 500px; 18 500px; 19 border: 1px solid red; 20 } 21 </style> 22 </head> 23 <body> 24 <div id="box"> 25 <div class="center-vertical"> 26 <p>士大夫撒飞洒盛世嫡妃</p> 27 <p>士大夫撒飞洒盛世嫡妃</p> 28 <p>士大夫撒飞洒盛世嫡妃</p> 29 <p>士大夫撒飞洒盛世嫡妃</p> 30 </div> 31 </div> 32 33 <script type="text/javascript"> 34 total = document.documentElement.clientHeight; 35 document.getElementById("box").style.height = total / 2 + "px"; 36 </script> 37 </body> 38 </html>
上面div的高度可以随着浏览器缩放改变高度 而里面的p的内容不管高度怎么变都可以垂直居中 关键就在于 .center-vertical 这个类