我正在使用以下代码在页面上显示背景图片:
#bg-pic {
top: 0px;
left: 0px;
position: fixed;
z-index: -1;
margin: 0px;
width: 100%;
}
#bg-pic > img {
width: 100%;
display: block;
}
<div id="bg-pic">
<img src="https://images.pexels.com/photos/259915/pexels-photo-259915.jpeg" />
</div>
一旦浏览器窗口的比例足够宽,此方法就可以正常工作。但是,如果我有一个很小的窗口,我希望图片仍然覆盖该页面,那么用width: 100%;
height: 100%;
代替是正确的。我该如何解决?
编辑:由于提供的答案不能解决我的实际问题,因此我们用一个示例进行描述:
答案 0 :(得分:3)
使用background属性代替img元素。
演示:
body {
background: url('image.jpg') center center / cover;
}
您的情况:
html, body {
min-height: 100%;
}
body {
margin: 0;
background: url('bg.jpg') center center / cover;
}
答案 1 :(得分:1)
您可以在image标签上使用object-fit和object-position属性。
#bg-pic{
top:0px;
left:0px;
position: fixed;
opacity: 0.18;
z-index: -1;
margin: 0px;
width: 100%;
height:100%;
}
#bg-pic img {
object-fit: cover;
object-position: 50% 50%;
width: 100%;
height: 100%;
}
您可以在CSS-Tricks上了解有关对象适配的更多信息:https://css-tricks.com/on-object-fit-and-object-position/
答案 2 :(得分:1)
您只需要在img样式标签中添加height:100vh;
,
您不能使用height:100%
,因为除非您为父级div
指定了静态高度,否则它将不会应用。
始终是vh
维度的更好选择。
#bg-pic {
top: 0px;
left: 0px;
position: fixed;
z-index: -1;
margin: 0px;
width: 100%;
}
<div id="bg-pic">
<img src="https://images.pexels.com/photos/259915/pexels-photo-259915.jpeg" style="width:100%; height:100vh; display: block;"/>
</div>
答案 3 :(得分:0)
body { background-image:url("../images/bg.jpg");
background-repeat: no-repeat;
background-size: 100% 100%; }
尝试
答案 4 :(得分:0)
尝试一下,它与跨浏览器兼容:
div {
position:relative;
}
img {
max-height: 100%;
max-width: 100%;
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
这假设您已为div设置了大小。
答案 5 :(得分:0)
您可能正在寻找background-size: contain
。与height: 100vh
配对应该可以达到预期的效果。
如果您需要水平居中放置图像,则可以为水平居中和垂直居中添加background-position: 50% 0%
或background-position: center;
。
#container-with-background {
background: url(https://images.pexels.com/photos/259915/pexels-photo-259915.jpeg);
background-repeat: no-repeat;
background-size: contain;
height: 100vh;
}
<div id="container-with-background">
</div>
如果您需要将图像放在<img>
标签中,则可以使用max-width: 100%
标签上的max-height: 100%
和<img>
,并在标签上固定高度,以达到相同的效果。容器-例如height: 500px
。将高度设置为100vh
将使其全屏显示。
#container {
height: 100vh; /* Can be set to fixed value if needed */
}
img {
display: block;
margin: 0 auto;
max-width: 100%;
max-height: 100%;
}
<div id="container">
<img src="https://images.pexels.com/photos/259915/pexels-photo-259915.jpeg">
</div>