css - DIV 折叠背景图像

标签 css html responsive-design media-queries

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

当视口(viewport)达到 > 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;
}

最佳答案

如果您知道背景图像的纵横比,可以使用一个技巧来防止框折叠 - 使用 border-box box-sizing,将高度设置为 0,并为 div 提供 padding-bottom反射(reflect)了那个比率。

.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

话虽如此,另一位评论者说得有道理;根据您的使用环境,也许这应该是内嵌图像而不是背景图像?

关于css - DIV 折叠背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27690200/

相关文章:

asp.net - 自动转义<'s and >'s

jquery - Bootstrap 样式输入类型的问题

javascript - 再次点击后,点击的图片不会回到上一张图片

html - 如何在 IE 中删除空 <select> 的空格

html - CSS悬停菜单不起作用

javascript - 单击它时菜单会出现(在移动 View 中)

html - 图像上的文字不起作用

html - CSS - 居中图像

php - 如何使用按钮清除<div>的内容

html - Zurb Foundation 中 small 的全宽搜索顶部栏