温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

CSS中overflow-y: visible;不起作用的原因是什么

发布时间:2021-05-27 11:47:28 来源:亿速云 阅读:423 作者:小新 栏目:web开发

这篇文章主要介绍CSS中overflow-y: visible;不起作用的原因是什么,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

场景

最近要做的一个需求是移动端的h6页面,要求有一排可选择的卡片, 超出容器部分可以左右滑动,同时每张卡片左上角要有一个删除按钮。如下图:

CSS中overflow-y: visible;不起作用的原因是什么

心想:so easy, 在父容器上加一个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%);
}

原本以为一切顺利,结果得到的结果如图:

CSS中overflow-y: visible;不起作用的原因是什么

看第矩形左上角的红色方块,原本为20 * 20的红色方块有一部分被隐藏了。我想应该是overflow影响的,所以想通过overflow-y: visible;来解决,结果是不行的。细心的朋友应该记得overflow的默认值就是visible。那么原因是什么呢?

Why

找了好久,大致了解到是如下原因

The computed values of &lsquo;overflow-x&rsquo; and &lsquo;overflow-y&rsquo; are the same as their specified values, except that some combinations with &lsquo;visible&rsquo; are not possible: if one is specified as &lsquo;visible&rsquo; and the other is &lsquo;scroll&rsquo; or &lsquo;auto&rsquo;, then &lsquo;visible&rsquo; is set to &lsquo;auto&rsquo;. The computed value of &lsquo;overflow&rsquo; is equal to the computed value of &lsquo;overflow-x&rsquo; if &lsquo;overflow-y&rsquo; is the same; otherwise it is the pair of computed values of &lsquo;overflow-x&rsquo; and &lsquo;overflow-y&rsquo;.
大致意思是,当overflow-x为scroll或者auto时,overflow-y被设置为auto,反之亦然。这就很尴尬了,那怎么解决这个问题呢。

ps: 上面那段话说是来自于w3c的文档,但是我找了半天没找到原文,麻烦找到了的小伙伴留个链接~ [手动狗头]

How

终究还是想让左上角的红色方块显示完整的,那么解决方案呢,我这里采用的是在container上添加以下样式

padding-top: 20px;
margin-top: -20px;

原理其实挺简单的,加了padding-top: 20px;后,绝对定位的红色方块就有空间显示了,不会超出容器体积,然后通过margin-top: -20px;抵消位置的变化.如图

CSS中overflow-y: visible;不起作用的原因是什么

ps: 第一个红色方块左边被遮住的部分同样的思路解决,即通过padding-left和margin-left来处理。

以上是“CSS中overflow-y: visible;不起作用的原因是什么”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI