【问题标题】:DIV collapses background imageDIV 折叠背景图像
【发布时间】:2014-12-29 13:51:49
【问题描述】:

我有一个包含 div (.tablet) 的部分容器。 section 和 Div 都是响应式的

当视口达到 > 400px 时,我想在我的 div (.tablet) 中显示背景图片

但是,除非我指定 px 宽度和高度,否则 div 会折叠并消失。它忽略了背景图像。就好像背景图片不存在,div也没有内容一样!

是否可以使用不会折叠的灵活背景图像创建响应 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 代码 ----------------------------------------------------

.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;
}

}

【问题讨论】:

  • nb。背景图像就是这样,背景而不是内容。因此,它受制于应用它的元素的尺寸。您需要将尺寸应用于.tablet,或者不使用背景图像,而是切换img 元素的显示
  • 如果你没有在 div 中放任何东西,只需使用 IMG 标签,然后将它们换掉。

标签: css html responsive-design media-queries


【解决方案1】:

如果您知道背景图像的纵横比,则可以使用一个技巧来防止框折叠 - 使用边界框框大小,将高度设置为 0,并给 div 一个 padding-bottom反映了这个比例。

.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

话虽如此,另一位评论者有一点;根据您的使用上下文,也许这应该是内嵌图像而不是背景图像?

【讨论】:

    【解决方案2】:

    尝试类似的方法。如果我确实理解了您的问题,它将使背景图像居中,并且也将保留口粮。

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

    使用包含会使您的图像变形或放大,但会完全可见。确保您的背景图片适合大屏幕,

    位置将从顶部和底部居中。 确保图像不会重复,因为这看起来很糟糕。 当然还有你想要作为背景的图片。

    【讨论】:

      【解决方案3】:

      我认为您的tabletonly div 的高度为 0,因为其中没有可显示的内容。 也许您可以指定min-height(即可以使用 vh、% 或 px)或使用内容填充 div。 很难说,因为我不知道你需要 div 做什么。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-19
        • 2011-07-28
        • 2023-04-04
        • 1970-01-01
        相关资源
        最近更新 更多