CSS教程:背景图

提出问题

使用 div 和 img 实现下图效果:

代码如下:

.box{
    width: 60px;
    height: 30px;
    background-color: red;
}
<div class="box">
    <img src="img/fdj.png" height="25">
</div>

实现效果如下图:

问题: 图片显示在左上角,不能水平居中、垂直居中显示

解决

使用 背景图 可以实现 图片定位

代码

.box2{
    width: 60px;
    height: 30px;
    background-color: red;
    /* 背景图,需要用 url() 函数才能显示图片 */
    background-image: url(img/fangdajing.png);
    /* 设置是否重复 */
    background-repeat: no-repeat;
    /* 设置背景图的大小,第一个值设置宽度、第二个值设置高度 */
    background-size: 20px 20px;
    /* 设置背景图的位置,第一个值:水平位置,第二个值:垂直位置 */
    background-position: 20px 5px;
    /* 水平居中: (背景的宽度 - 图片的宽度 )/2 */
    /* 垂直居中: (背景的高度 - 图片的高度 )/2 */
}
<div class="box2">

</div>

原文出处:/show_1IX7apB17TLY.html