iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 2
0
自我挑戰組

網頁學習日誌系列 第 2

CSS : position 絕對定位與相對定位

https://ithelp.ithome.com.tw/upload/images/20200411/20107321bhjMvVKsQr.png

上面商品圖片的hot可以跟圖片重疊,這是float絕對做不到的事情,需要透過絕對定位來處理

原理:

  1. 在外層新增div (Product_block_hot)並設為相對定位(relative)讓hot區塊只能在該範圍內移動,但hot區塊要設為絕對定位(absolute)才有效。
  2. hot區塊再用top、bottom、left、right後面加上數值調整位置

HTML:

    <div class="Product_block_hot">
        <span class="Product_hot_icon">Hot</span>
        <img src="product_1.png" alt="">
    </div>

CSS:

.Product_block_hot{
    position: relative;//設為相對定位(relative)
    text-align: center;
    border:2px solid black;
}

//hot紅色區塊
.Product_hot_icon{
    position: absolute;//設為絕對定位(absolute)
    font-weight: bold;
    top: 0px;
    right : 0px; //右邊上面都設0,則出現在右上方
    color: white;
    display: block;
    background: red;
    width: 40px;
    height: 19px;
    text-align: center;
}

結果如下:

https://ithelp.ithome.com.tw/upload/images/20200411/20107321ij6NlIhk3s.png

就算把圖片刪除,新增div 背景設為綠色也是同樣

    <div class="Product_block_hot">
        <span class="Product_hot_icon">Hot</span>
        <div class="color" style="width:300px;height:240px;background-color:green;">
        </div>
    </div>

結果如下:

https://ithelp.ithome.com.tw/upload/images/20200411/2010732102vPkO32Dq.png

z-index也是搭配絕對定位的重要語法,上面的例子再加上本日推薦的區塊
未加上前效果如下:

https://ithelp.ithome.com.tw/upload/images/20200411/20107321VxJt6UaNNO.png

HTML:

    <div class="Product_block_hot">
        <span class="Product_hot_icon">Hot</span>
        <div class="color" style="width:300px;height:240px;background-color:green;">
        </div>
        <div class="title">本日推薦</div>
    </div>

CSS:新增本日推薦css

    .title {
        position: absolute;
        width: 300px;
        height: 20px;
        background: blue;
        color: white;
        font-weight: bold;
        top: -10px;
    }

如果想要讓本日推薦藍色區塊移到hot上面可在這兩個css加入z-index,後面數字越大則越在上面

CSS:

.Product_hot_icon{
    z-index: 18;
    position: absolute;
    font-weight: bold;
    top: 0px;
    right : 0px;
    color: white;
    display: block;
    background: red;
    width: 40px;
    height: 19px;
    text-align: center;
}
.title{
    z-index: 19;//數字越大越上層
    position: absolute;
    width: 300px;
    height: 20px;
    background: blue;
    color: white;
    font-weight: bold;
    top: -10px;
}

結果如下:

https://ithelp.ithome.com.tw/upload/images/20200411/20107321Yjxf2fcff3.png


上一篇
RWD : LOGO 與選單的排版
下一篇
CSS : display屬性-區塊和行內元素差異
系列文
網頁學習日誌30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言