【发布时间】:2015-03-05 13:20:56
【问题描述】:
我正在尝试将背景图片设置为 div,但效果不如预期。
我有一个页眉、一个页脚和一个侧边栏。页眉高 80 像素,页脚高 10 像素,侧边栏从屏幕左侧延伸 250 像素。我希望我的内容 div 成为剩余的屏幕。
我写了以下代码:
<!DOCTYPE html>
<html>
<head>
<title>Testing My HTML and CSS</title>
<style>
* {
padding: 0;
margin: 0;
font-family: arial;
}
body .sidebar {
display:block;
}
body.loaded .sidebar {
display:none;
}
.header {
background-color: black;
height: 80px;
width: 100%;
text-align: center;
line-height: 2;
color: white;
}
.sidebar {
background-color: #ebebeb;
position: absolute;
width: 200px;
top: 80px;
bottom: 0;
padding-top: 10px;
}
.sidebar li {
color: black;
list-style-type: none;
margin-top: 30px;
width: 100%;
}
.sidebar li a {
text-decoration: none;
margin-top: 30px;
margin-left: 30px;
background-color: #9da1a4;
width: 100px;
padding: 8px;
border: 1px solid silver;
border-radius: 5px;
}
.content {
height: 340px;
width: 523px;
background-image: url("arbor.jpeg");
background-size: cover;
}
.menu-btn {
background-image: url("menu.png");
float: left;
height: 48px;
width: 44px;
margin-left: 50px;
margin-top: -35px;
}
.footer {
width:100%;
height:30px;
position:absolute;
text-align: center;
color: white;
background-color: black;
padding-top: 10px;
bottom:0;
left:0;
}
</style>
<script src="js/jquery.min.js"></script>
</script>
</head>
<body>
<div id="home">
<div class="header">
<h1>Hello, World!</h1>
<div class="menu-btn"></div>
</div>
<div class="sidebar">
<li><a href="#">Hello</a></li>
</div>
<div class="content">
</div>
<div class="footer">
<p>Hello</p>
</div>
</div>
<script>
$(function() {
$('body').addClass('loaded');
});
$(".menu-btn").on("click", function(){
$(".sidebar").slideToggle(600);
});
</script>
</body>
</html>
可以在this jsfiddle看到。
我的目标是将.content 中的图像设置为背景。
我尝试了background-attachment: fixed;、background-size: cover 等,但它不适合我的需求。
有什么建议吗?
谢谢, erip
编辑
jsfiddle 有点误导,所以这里是正在发生的事情的图片
左上角的菜单按钮驱动下拉菜单。
编辑 2
将.content中的CSS更改为:
.content {
height: 100vh;
width: 100%;
background-image: url("arbor.jpeg");
background-size: cover;
}
我还有两个问题:
- 我希望从最左侧到左侧 250 像素(即侧边栏的空间)没有图像
- 页面现在滚动。我希望图像适合单个屏幕。
我试图通过使用left: 250px; 和padding-left: 250px; 来解决第一个问题,但都没有成功。
我希望我已经提供了足够的信息。
【问题讨论】:
-
看起来它正在你的小提琴上工作。
-
查看有问题的编辑。
-
@erip 你希望图片在页眉和页脚正下方占据整个屏幕
-
为什么不把.content的宽度设置为100%呢?这里看看jsfiddle.net/kpkzf7wo/1
-
如果您也需要在多个图像上使用类似功能,您可以使用这个 jquery 插件 - johnpolacek.github.io/imagefill.js