css切背景图片(background-position)

给元素添加背景图片的方式有很多,个人总结的有:

用img插入图片;

css3的方式手动绘图;

单独用background-image单独插入图片;

其中用background-image有两种方法,一种是采用的单一照片来设置,另一种就是采用一张整图来切:

会用到的属性有:

background-positon:x轴起点 y轴起点;
background-size:背景图片的大小;
width:终点x轴位置;
height:终点y轴位置;

例如:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .img-total {
            cursor: pointer;//定义鼠标移入样式
            width: 30px;//x轴终点
            height: 30px;//y轴终点
            background-image: url(images/position.png);//图片位置
            background-size: 120px 30px;//背景图片大小
            display: inline-block;
        }

        .img-home {
            background-position: 0 0;//起点位置
            background-color: #23ccfe;
        }

        .img-favorite {
            background-position: -31px 0;
            background-color: #095f8a;
        }

        .img-cart {
            background-position: -61px 0;
            background-color: #1b961b;
        }

        .img-user {
            background-position: -91px 0;
            background-color: #94df94;
        }
    </style>
</head>
<body>
<div style="background-color: #f8f8f8; height:300px; padding-top:30px;">
    <span class="img-total img-home"></span>
    <span class="img-total img-favorite"></span>
    <span class="img-total img-cart"></span>
    <span class="img-total img-user"></span>
</div>
</body>
</html>

其中背景图片是用一张大图来切的:

显示效果:

可以通过:background-position还有width,height属性来控制起始位置来控制切点,要注意的是因为(0,0)点默认是左上角,而图片在原点的右下角(第四象限)所以position的坐标为负值;

原文地址:https://www.cnblogs.com/wangrongxiang/p/5283034.html