2014-12-29 135 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。