css 背景(background)属性、背景图定位

background属性:

Background属性是css中应用比较多,且比较重要的一个属性,它是负责给盒子设置背景图上和背景颜色的,background是一个复合属性,它可以分解成如下几个设置项:

1background-color 设置背景颜色

2background-image 设置背景图片地址

3background-repeat 设置背景图片如何重复平铺

4background-position 设置背景图片的位置

5background-attachment 设置背景图片是固定还是随着页面滚动条滚动

实际应用中,可以用background属性将上面所有的设置项放在一起,而且也建议这么做,这样做性能更高,而且兼容性更好,如:”background:#00ff00 url(bgimage.gif) no-repeat left center fixed”,其中#00ff00是设置background-color;url(bgimage.gif)是设置background-image;no-repeat是设置background-repeat;left center是设置background-position;fixed是设置background-attachment;各设置项用空格隔开,有的设置项也可以不写,它会使用默认值。

background-size使用:

--length:

固定的值,如:100px 100px

--percentage:

百分比,如:90% 90%

--cover:

背景图片的较小边放大到目标大小结束

--contain:

背景图片的较大边放大到目标大小结束

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>background属性</title>
    <style type="text/css">
        .box{
            width:400px;
            height:200px;
            border:1px solid #000;
            margin:50px auto 0;
            /* 设置背景图片 */
            background-image:url("images/头像2.png");
            /* repeat-x:只平铺x轴方向 */
            /*background-repeat:repeat-x; */
            /* repeat-y:只平铺y轴方向 */
            /*background-repeat:repeat-y;*/
            /* no-repeat:只平铺一次 */
            background-repeat:no-repeat;
            /* repeat:默认值 平铺所有的 */
            /*background-repeat:repeat;*/

            /* 设置背景图片的位置,第一个参数表示水平方向、第二个参数表示垂直方向的位置
               水平方向:left center right
               垂直方向:top center bottom
             */
            /*background-position:center center;  /left:左右位置 top:上下位置 *!*/

            /* background-position可以是方向词,也可以是数值 */
            /*background-position:30px 10px;*/
            /*background-position:-10px 20px;*/

            /* 合并写法: */
            background:url("images/头像2.png") -10px 10px no-repeat cyan;
        }
    </style>
</head>
<body>
    <div class="box">
        背景图片
    </div>

</body>
</html>

页面效果:

背景图定位代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>背景定位</title>
    <style type="text/css">
        .box{
            width:200px;
            height:200px;
            border:2px solid black;
            margin:50px auto 0;

            background-image:url("images/hellokity.jpg");
            background-repeat:no-repeat;
            background-position:-159px -491px;
        }
    </style>
</head>
<body>
    <div class="box"></div>

</body>
</html>

猜你喜欢

转载自www.cnblogs.com/reyinever/p/10630032.html
今日推荐