CSS中overflow-y: visible;不起作用的原因分析及解決方法

場(chǎng)景
最近要做的一個(gè)需求是移動(dòng)端的h5頁(yè)面,要求有一排可選擇的卡片, 超出容器部分可以左右滑動(dòng),同時(shí)每張卡片左上角要有一個(gè)刪除按鈕。如下圖:
心想:so easy, 在父容器上加一個(gè)max-width: 200px; white-space: nowrap; overflow-x: auto;不就搞定了嘛。Demo如下:
<div class="container"> <div class="son"> <div class="delete_btn"></div> </div> <div class="son"> <div class="delete_btn"></div> </div> <div class="son"> <div class="delete_btn"></div> </div> </div> .container { max-width: 500px; overflow-x: auto; white-space: nowrap; } .son { display: inline-block; width: 200px; height: 200px; background-color: lightblue; position: relative; margin-right: 20px; } .delete_btn { width: 20px; height: 20px; position: absolute; top: 0; left: 0; background-color: red; transform: translateX(-50%) translateY(-50%); }
原本以為一切順利,結(jié)果得到的結(jié)果如圖:
看第矩形左上角的紅色方塊,原本為20 * 20的紅色方塊有一部分被隱藏了。我想應(yīng)該是overflow影響的,所以想通過(guò)overflow-y: visible;來(lái)解決,結(jié)果是不行的。細(xì)心的朋友應(yīng)該記得overflow的默認(rèn)值就是visible。那么原因是什么呢?
Why
找了好久,大致了解到是如下原因
The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.
大致意思是,當(dāng)overflow-x為scroll或者auto時(shí),overflow-y被設(shè)置為auto,反之亦然。這就很尷尬了,那怎么解決這個(gè)問(wèn)題呢。
ps: 上面那段話說(shuō)是來(lái)自于w3c的文檔,但是我找了半天沒(méi)找到原文,麻煩找到了的小伙伴留個(gè)鏈接~ [手動(dòng)狗頭]
How
終究還是想讓左上角的紅色方塊顯示完整的,那么解決方案呢,我這里采用的是在container上添加以下樣式
padding-top: 20px; margin-top: -20px;
原理其實(shí)挺簡(jiǎn)單的,加了padding-top: 20px;后,絕對(duì)定位的紅色方塊就有空間顯示了,不會(huì)超出容器體積,然后通過(guò)margin-top: -20px;抵消位置的變化.如圖
ps: 第一個(gè)紅色方塊左邊被遮住的部分同樣的思路解決,即通過(guò)padding-left和margin-left來(lái)處理。
總結(jié)
以上所述是小編給大家介紹的CSS中overflow-y: visible;不起作用的原因分析及解決方法,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
css 設(shè)置overflow:scroll 滾動(dòng)條的樣式
這篇文章主要介紹了css 設(shè)置overflow:scroll 滾動(dòng)條的樣式 ,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-07-25深入理解CSS overflow:hidden——溢出,坍塌,清除浮動(dòng)
這篇文章主要介紹了深入理解CSS overflow:hidden——溢出,坍塌,清除浮動(dòng)的相關(guān)資料,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-03
詳解CSS中zoom屬性或overflow:auto屬性清除浮動(dòng)的作用
使用CSS的overflow屬性防止float撐開(kāi)div的方法
css 給div添加滾動(dòng)并隱藏滾動(dòng)條