2013-06-01 32 views
0

我有一個圖像背景,我想要在不同的設備上顯示div,問題是我必須給圖像的高度以正確適合它。現在在不同的手機上,我必須用不同的像素來調整高度。例如在iphone 65px的作品肖像模式,但不適用於風景等。有沒有一種方法,div只是被調整高度以覆蓋100%的背景圖像? 這裏是我的代碼用於媒體查詢和高度問題的css

<style> 
    div.testing { 
     height: 95px; 
     background-image: url(/myimageurl); 
     background-repeat: no-repeat; 
     background-size: 100%; 
    } 
    @media screen and (max-width: 320px) { 
     /* iphone portrait */ 
     div.testing { 
      height: 65px; 
     } 
    } 
    @media screen and (min-width: 321px) and (max-width: 480px) { 
     /* iphone portrait */ 
     div.testing { 
      height: 80px; 
     } 
    } 
    </style> 

    <div class="testing">&nbsp;</div> 
+0

如果我使用背景大小:封面然後寬度成爲一個問題 – Autolycus

回答

1

你可以使用背景尺寸:蓋;

.thing { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover; 
    -moz-background-size: cover; 
    -o-background-size: cover; 
    background-size: cover; 
} 

但你爲什麼要使用背景圖片?如果你可以使用普通的圖像,你可以做這樣的:

.thing { 
    width: 100%; 
    max-width: [your biggest width]; 
} 

.thing img { 
    display: inline-block; 
    width: 100%; 
    height: auto; 
} 

ALSO

我會建議在最大寬度翻轉你的心態,並首次啓動小屏幕,使用最小寬度和獲取大。

而且你並不真的需要div.testing - 它正好可以.testing

如果你正在使用的背景圖像一個很好的理由......你應該調查使得DIV -

.thing { 
    height: 0; 
    padding-bottom: 30%; /* play with this */ 
} 

這將保持比例...但它只在特定情況下有用。

具有實際圖像的完整jsfiddle會很有用。

祝你好運!

0

鳥巢背景DIV中的股利和高度設置爲100%