pc端实现 网页居中显示 且自适应
通过给最外层添加绝对定位和translate(-50%,-50%) scale(ratio)来实现居中且适度缩放。
<!DOCTYPE html > <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title>pc端实现 网页居中显示 且自适应</title> <style> *{margin: 0; padding: 0;} .evt-content{ width: 800px; height: 1000px; border: #ccc 2px solid; margin: 0 auto;} </style> </head> <body> <div class="evt-content"> <img src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" alt=""> <img src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" alt=""> <img src="https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png" alt=""> </div> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> <script type="text/javascript"> (function(){ function createResponsiveStyle() { var style = document.createElement("style"); style.type = "text/css"; document.head.appendChild(style); return { setStyle: function (text) { style.innerHTML = ""; if( style.styleSheet ){ style.styleSheet.cssText = text; } else { style.innerHTML = text; } }, getRespStyle: function(){ var ratio = Math.max(0.65, Math.min(1, window.innerHeight/960)); return ".evt-content{" + "position:absolute;height:800px;left:50%;top:50%;" + "-webkit-transform:translate(-50%,-50%) scale("+ratio+");" + "transform:translate(-50%,-50%) scale("+ratio+");" + "-webkit-transform-origin:50% 50%;" + "transform-origin:50% 50%;" + "}"; } } } var respStyle = createResponsiveStyle(); respStyle.setStyle(respStyle.getRespStyle()); $(window).resize(function () { respStyle.setStyle(respStyle.getRespStyle()); }); })(); </script> </body> </html>
给心灵一个纯净空间,让思想,情感,飞扬!