2014-12-29 200 views
0

我有一個容器div(.tablet)。兩個部分和DIV響應DIV崩潰背景圖像

當視圖端口達到> 400像素,我想在div來顯示背景圖像(.tablet)

然而,除非我指定一個像素的寬度和高度,在div塌陷並消失。它忽略了背景圖像。這幾乎就像背景圖片不存在,div沒有內容!

是否有可能創建一個靈活的背景圖像,不崩潰的resposnive DIV?我想要背景圖片填充DIV並以div大小進行響應?

我已經使用以下規則與.tabletonly DIV試圖

background-size: cover; 
background-position: center; 
background-attachment: fixed; /* Fixbackground * */ 

// ------------------------ --------------------------------------------

HTML 

<!DOCTYPE html PUBLIC> 

<head> 
    <title></title> 
     <link rel="stylesheet" type="text/css" href="styles/style1.css"/> 

</head> 
<body> 

<div id="wrapper"> 
<div id="section"> 




<div id="tabletonly" class="span_1_of_2"> 
    <div><div> 
    </div> 


</div> // end wrapper 
</body> 
</html> 

CSS code ----------------------------------------

.span_1_of_2 { 
    width: 45%; 
    position: relative; 
} 


img { 
    max-width: 100%; 
} 



@media screen and (min-width: 400px) { 

#tabletonly div{ 
    background: url("images/shop.jpg"); 
    background-repeat: no-repeat; 
} 

}

+0

nb。背景圖片就是那個,背景而不是內容。因此,它受到應用元素的尺寸的限制。您將需要將尺寸應用於'.tablet',或者,而不是使用背景圖像,切換「img'元素的顯示 – SW4

+1

如果您沒有在div中放入任何東西,只需使用IMG標記並交換那些了。 – jleggio

回答

1

如果您知道背景圖像的寬高比,您可以使用一種技巧來防止摺疊 - 使用邊框框大小,將高度設置爲0,併爲div指定一個填充底部反映了這一比例。

.image-box { 
    background: url('http://placehold.it/600x300/eee/ccc'); 
    background-size: cover; 
    height: 0; 
    padding-bottom: 50%; /* match this to the aspect ratio of your picture */ 
} 

fiddle

如此說來,其他的評論者有一個點;取決於你的使用環境,也許這應該是一個內聯圖像而不是背景圖像?

0

嘗試類似的東西。如果我理解你的問題,它將以背景圖像爲中心,並保持配給。

background-size:contain; 
background-position: center center; 
background-repeat:no-repeat; 
background-image: url(../images/YourBackgroundImage.png); 

使用包含將skink或enlage您的圖像,但將完全可見。確保你的背景圖像足夠大屏幕,

該位置將從頂部和底部居中。 確保圖像不會重複,因爲看起來很糟糕。 當然還有你想作爲背景的圖片。

0

我認爲你的tabletonly div的高度爲0,因爲它沒有可顯示的內容。 也許你可能會指定min-height(即可能使用vh,%或px)或者將div與內容一起填充。 很難說,因爲我不知道你需要什麼div。