簡體   English   中英

縮放和居中網頁以適合任何設備/窗口尺寸

[英]Scaling and centering a web page to fit any device/window dimensions

我有一個針對特定寬度和高度設計的Web應用程序(Cordova)。 無論我使用哪種設備(電話,平板電腦,瀏覽器),我都希望文檔主體按比例縮小。 如果設備大於我設計的尺寸,則文檔主體不應按比例放大,而應在窗口中居中。 我認為我已經將比例計算降低了,但是我似乎無法使主體和內容垂直和水平居中。

這是一個演示(演示的尺寸為300x400小):

http://jsfiddle.net/D2e4W/

調整“結果”窗口的大小以查看其縮放。 我已經使其垂直工作(僅適用於Chrome),但是水平縮小會使其向右移動。 我樂於接受與這里所講的完全不同的方法。

相關代碼:

<body>
    <div id='div1'></div>
</body>

<script>
var max_width  = 300;
var max_height = 400;
window.addEventListener('resize', on_window_resize);
on_window_resize();

function on_window_resize()
{
    //if either window dimension is less than max, scale body to fit
    var h_scale = window.innerHeight / max_height;  
    var w_scale = window.innerWidth / max_width;        
    var page_scale = 1;
    if (h_scale < 1 || w_scale < 1) 
    {
        page_scale = (h_scale < w_scale) ? h_scale : w_scale;
    }   

    //display scale string    
    var div1 = document.getElementById('div1');
    div1.innerHTML = "scale: " +  page_scale.toFixed(2);


    //scale body using webkit transforms
    var scale_str = "scale(" + page_scale + ")";

    document.body.style.webkitTransform = scale_str;
    document.body.style.transform       = scale_str;    
    //document.body.style.webkitTransformOrigin = "0 0";
    //document.body.style.transformOrigin = "0 0";

    //div1.style.webkitTransform = scale_str;
    //div1.style.transform       = scale_str;   
    //div1.style.webkitTransformOrigin = "0 0";
    //div1.style.transformOrigin = "0 0";

}
</script>

<style>
body 
{
    overflow:hidden;    
    background-color: #444444;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;    
}

#div1
{
    overflow = 'hidden';
    width: 300px;
    height: 400px;
    background-color: #dd4444;
    font-size: 60px;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}
</style>

更合適的方法是在CSS中使用媒體查詢,該查詢根據窗口/視圖的大小調整樣式:

例如,您的300x400框:

body 
{
    overflow:hidden;    
    background-color: #444444;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;    
}

#div1
{
    overflow = 'hidden';
    width: 150px;
    height: 200px;
    background-color: #dd4444;
    font-size: 60px;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

@media all and (min-width: 300px) and (max-width:1000px) {
  #div1 {
    width: 300px;
    height: 400px;
    background-color: green;
  }
}

小提琴: http : //jsfiddle.net/44aAy/2/

當窗口的最小寬度為300像素,但最大不超過1000像素時,框將更改大小並變為綠色。 再次將方框縮小,然后變成紅色。

有一些框架,例如Twitter Bootstrap,Skeleton以及其他內置用於響應式Web設計的框架。

似乎設置的寬度迫使其顯示在右側。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM