最近要作的一个需求是移动端的h5页面,要求有一排可选择的卡片, 超出容器部分能够左右滑动,同时每张卡片左上角要有一个删除按钮
。以下图:spa
心想:so easy, 在父容器上加一个max-width: 200px; white-space: nowrap; overflow-x: auto;
不就搞定了嘛。Demo以下:code
<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%); }
本来觉得一切顺利,结果获得的结果如图:orm
看第矩形左上角的红色方块,本来为20 * 20的红色方块有一部分被隐藏了。我想应该是overflow影响的,因此想经过overflow-y: visible;来解决,结果是不行的。细心的朋友应该记得overflow的默认值就是visible。那么缘由是什么呢?blog
找了很久,大体了解到是以下缘由ip
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’.
大体意思是,当overflow-x为scroll或者auto时,overflow-y被设置为auto,反之亦然。这就很尴尬了,那怎么解决这个问题呢。ci
ps: 上面那段话说是来自于w3c的文档,可是我找了半天没找到原文,麻烦找到了的小伙伴留个连接~ [手动狗头]文档
终究仍是想让左上角的红色方块显示完整的,那么解决方案呢,我这里采用的是在container
上添加如下样式it
padding-top: 20px; margin-top: -20px;
原理其实挺简单的,加了padding-top: 20px;
后,绝对定位的红色方块就有空间显示了,不会超出容器体积,而后经过margin-top: -20px;
抵消位置的变化.如图io
ps: 第一个红色方块左边被遮住的部分一样的思路解决,即经过padding-left和margin-left来处理。form