1. 程式人生 > 其它 >實現圖片背景的兩種方式

實現圖片背景的兩種方式

技術標籤:css+htmlcsshtmlhtml5css3

實現圖片背景的兩種方式

1)通過css樣式實現

<div class="box">
    <a class="logo_link" href="www.bilibili.com">
        <img class="header_logo" src="../static/images/bili_logo.png" alt="">
    </a>
</div
>
* {
    padding: 0px;
    margin: 0px;
}
.box {
    width: 100%;
    height: 120px;
    background-image: url("../static/images/c60fe2b9198b5e5bff2a95984e6e4713d437850a.jpg");
    background-position: left top; /*定位取值[left top|left center|center top ...]*/
    background-size: 100% 120px; 
    background-repeat
: no-repeat; /*no-repeat會使圖片會鋪滿,但尺寸不合適時會伸縮*/ } .logo_link .header_logo { height: 60px; width: auto; }

在這裡插入圖片描述

2)通過img實現

結合positionz-index屬性實現img元素變成背景圖片

<div class="box">
    <img class="banner_bg" src="../static/images/c60fe2b9198b5e5bff2a95984e6e4713d437850a.jpg" alt
="">
<a class="logo_link" href="www.bilibili.com"> <img class="header_logo" src="../static/images/bili_logo.png" alt=""> </a> </div>
* {
    padding: 0px;
    margin: 0px;
}
.box {
    width: 100%;
    height: 120px;
    position: relative;
}
.banner_bg {
    width: 100%;
    height: 120px;
    position: absolute;
    left: 0px;
    right: 0px;
    z-index: -1;
}
.logo_link .header_logo {
    height: 60px;
    width: auto;
}

在這裡插入圖片描述

總結

第二種方式相較於第一種方式更為靈活,如果背景圖片存在更換需求,則採用第二種方式比較適合,通過js修改html中的url來實現圖片的更換。