本篇談三件事:讓背景圖只出現一次、把圖片放到指定位置、以及用百分比來定位。
搭配閱讀理論篇:CSS 教程(一):把背景相關觀念一次學透。
把 background-repeat 設為 no-repeat,圖片就不會被平鋪,只在起始位置出現一張。
<html>
<head>
<style type="text/css">
body
{
background-image: url('/i/eg_bg_03.gif');
background-repeat: no-repeat
}
</style>
</head>
<body>
</body>
</html>
加上 background-position 就能把圖放到想要的位置;若同時希望它隨視窗固定,還要搭配 background-attachment:fixed。
<html>
<head>
<style type="text/css">
body
{
background-image:url('/i/eg_bg_03.gif');
background-repeat:no-repeat;
background-attachment:fixed;
background-position:center;
}
</style>
</head>
<body>
<p><b>註:</b>要在 Mozilla 系瀏覽器中看到固定效果,background-attachment 必須設為 fixed。</p>
</body>
</html>
百分比適合做「隨容器比例伸縮」的定位。要特別記住:百分比同時作用於容器與圖片本身,兩側的對應比例點會互相對齊。
<html>
<head>
<style type="text/css">
body
{
background-image: url('/i/eg_bg_03.gif');
background-repeat: no-repeat;
background-attachment:fixed;
background-position: 30% 20%;
}
</style>
</head>
<body>
<p><b>註:</b>要在 Mozilla 系瀏覽器中看到固定效果,background-attachment 必須設為 fixed。</p>
</body>
</html>
把 30% 20% 改成 50% 50% 就是置中,改成 100% 0 則是右上角——多試幾組數值,你對百分比定位的直覺就會建立起來。