背景圖片
我們會時常遇到設置背景圖片,這裏簡單地總結下兩種方法:
1.background-image
background-image,顧名思義是背景圖片的意思,設置父親元素,然後通過background-image:url(‘圖片的相對路徑’);的辦法來設置背景圖片,可以將本地圖片上傳到github,qq 空間或者base64圖片 來獲取相對路徑.
下面有一段簡單的代碼實例:
/*WXML代碼*/
<view class='weather-wrapper'>
<view class="temp">12°</view>
<view class='weather'>晴天</view>
</view>
/*CSS代碼*/
page{
width:100%;
height:100%;
}
.temp{
text-align: center;
font-size: 200rpx;
line-height:1.4;
opacity: 0.8;
}
.weather{
text-align: center;
font-size:40rpx;
line-height:1.4;
opacity:0.65;
}
.weather-wrapper{
background-image: url(https://raw.githubusercontent.com/udacity/cn-wechat-weather/2-4/images/sunny-bg.png);
padding-top: 174rpx;
padding-bottom: 250rpx;
background-repeat: no-repeat;
background-size: 100% 100%;
}
效果圖如下:
以上首先設置了父親元素,然後再通過background-image的方式來設置背景圖片.
2.position方法
設置父親元素爲relative,然後讓想設置的圖片首先爲子元素,然後設置爲absolute,然後通過top,left定位的方式來定位,然後設置這個圖片的寬度和高度爲100%.
<view class='weather-wrapper'>
<view class="temp">12°</view>
<view class='weather'>晴天</view>
<image class='weather-bg' src='/images/sunny-bg.png'></image>
</view>
page{
width:100%;
height:100%;
}
.temp{
text-align: center;
font-size: 200rpx;
line-height:1.4;
opacity: 0.8;
}
.weather{
text-align: center;
font-size:40rpx;
line-height:1.4;
opacity:0.65;
}
.weather-wrapper{
position:relative;
padding-top: 174rpx;
padding-bottom: 250rpx;
}
.weather-bg{
position: absolute;
top:0;
left:0;
width:100%;
height:100%;
z-index:-1;
}
效果圖:
以上是兩種方法,沒有好壞之分,但圖片建議使用相對路徑而不是本地圖片.