[英]CSS image is not covering whole screen
我想讓我的CSS圖像覆蓋整個屏幕,我是從JS數組中隨機選擇一個圖像。 它顯示的圖像,但不顯示完美的整頁背景圖像。
main.html
<html>
<head>
<link rel="stylesheet" href="main.css">
</head>
<body>
<button id = "button1">Click</button>
<script src = "main.js"></script>
</body>
</html>
main.js
document.getElementById("button1").addEventListener("click", function(){
showImage();
});
...
function showImage(){
document.write('<img class = "bg" src="'+theImages[whichImage]+'">');
}
main.css
img.bg {
/* Set rules to fill background */
min-height: 100%;
min-width: 1024px;
/* Set up proportionate scaling */
width: 100%;
height: auto;
/* Set up positioning */
position: fixed;
top: 0;
left: 0;
}
@media screen and (max-width: 1024px) { /* Specific to this particular image */
img.bg {
left: 50%;
margin-left: -512px; /* 50% */
}
}
我同意設置document.body.style['background-image']
屬性是最好的方法,尤其是因為它允許您處理與屏幕形狀不匹配的圖像形狀(使用background-position
和background-size
修復background-size
)。 如果仍要使用<img>
,則可以使用CSS3長度單位vh
, vw
。 在這里可以找到對現代瀏覽器的支持。
img.bg {
width: 100vw;
height: 100vh;
}
請注意,即使body
元素(即存在滾動條),圖像也不會變得高於視口。
那是什么樣的CSS? 我也不建議使用vw / vh。
使用標准背景尺寸和位置(例如,
/*background-image: url(../images/background.png);*/ optional
background-size: cover;
background-repeat: no-repeat;
background-position: left top;
你可以隨時添加
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
全面的跨瀏覽器兼容性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.