從大圖中選取部分區域做爲目標圖標css
by:授客 QQ:1033553122html
1、圖片素材ui
圖片素材以下(大小:137px * 264px),圖中從上到下,連續存放了兩張100px * 100px的圖url
2、HTML代碼spa
html代碼以下:ssr
<!DOCTYPE html>3d
<html>htm
<head>blog
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />圖片
<style type="text/css">
.icon {
width:100px; /*--設置背景圖顯示區域寬度--*/
height:100px;/*--設置背景圖顯示區域高度--*/
border:1px solid red;
background-image:url(icons.png); /*--設置背景圖像--*/
/*--no-repeat 不容許圖像在任何方向上平鋪,repeat-y,repeat-x分別容許圖片在y,x方向上平鋪--*/
background-repeat:no-repeat;
}
</style>
</head>
<body>
<div class="icon up"><p>圖片上半部分</div>
<div class="icon down"><p>圖片下半部分</p></div>
</body>
</html>
顯示效果:
修改代碼以下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type="text/css">
.icon {
width:100px; /*--設置背景圖顯示區域寬度--*/
height:100px;/*--設置背景圖顯示區域高度--*/
border:1px solid red;
background-image:url(icons.png); /*--設置背景圖像--*/
/*--no-repeat 不容許圖像在任何方向上平鋪,repeat-y,repeat-x分別容許圖片在y,x方向上平鋪--*/
background-repeat:no-repeat;
}
.up {
background-position: 0px 0px;
}
.down {
background-position: 0px -100px;
}
</style>
</head>
<body>
<p>圖片上半部分</p>
<div class="icon up"></div>
<p>圖片下半部分</p>
<div class="icon down"></div>
</body>
</html>
顯示效果:
3、總結
載入背景圖片,根據須要設置展現區寬度和高度,及背景圖片的位置,讓其目標圖片內容「剛好落在」展現區,其中主要是利用了background-position的一些特性,圖解以下
說明:
background-position:0 0
背景圖片的左上角和所在容器左上角對齊,超出的部分隱藏。等同於 background-position: left top、background-position:0% 0%
background-position: 100% 100%
背景圖片的右下角和所在容器的右下角對齊,超出的部分隱藏。等同於background- positon: right bottom、background-positon:容器(container)的寬度-背景圖片的寬度,容器 (container)的高度-背景圖片的高度
background-position: 0 -100px;。
背景圖片從所在容器左上角的地方向上移動100px,超出的部分隱藏。
background-position: 20 18x;。
背景圖片從所在容器左上角的地方向右移20px,向下移18px,超出的部分隱藏。
background-position: -20 -18x;。
背景圖片從所在容器左上角的地方向左移-20px,向上移-18px,超出的部分隱藏。
參考連接:
http://www.w3school.com.cn/css/css_background.asp
http://www.w3school.com.cn/cssref/pr_background-position.asp