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>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM