編碼的世界 / 優質文選 / 生涯

設置全屏的背景圖片


2022年3月18日
-   

關鍵詞:Full size stretched background image,CSS 2和CSS 3的實現
我們有時期望背景圖片自動拉伸占據所有空間,使用CSS 3做起來並不麻煩,定義如下的CSS:
body {
background:#3d71b8 url(../back_main.png);
background-size: 100%;
background-position:center;
}

但是background-siz是CSS 3的屬性,並不是所有的瀏覽器都支持。使用CSS 2的一種實現如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome to my blog</title>
<style type="text/css">
#bg {
position:fixed;
top:0;
left:0;
width:100%;
height:100%;
}
#bg img {
position:absolute;
left:0;
right:0;
bottom:0;
margin:auto;
width:100%;
height:100%;
z-index:-1;
}
</style>
</head>
<body>
<div id="bg">
<img src="back_main.png" alt="">
</div>
<div>
Your content goes here!
</div>
</body>
</html>

熱門文章