如何实现仅当出现垂直滚动条时才为容器添加右侧内边距?
仅用CSS实现滚动条存在时添加右侧内边距的方案
可以实现,下面提供两种适配不同浏览器的CSS方案:
方案一:利用:has()伪类(现代浏览器支持)
:has()伪类可以检测容器是否存在滚动条,以此动态切换内边距。该方案支持Chrome 101+、Firefox 121+、Safari 15.4+版本:
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } .container { display: flex; flex-direction: column; overflow-y: auto; height: 70px; width: 100px; border: 1px solid red; padding-right: 0; /* 默认无内边距,内容占满容器宽度 */ } /* 检测到垂直滚动条时,添加右侧内边距 */ .container:has(::-webkit-scrollbar) { padding-right: 10px; } /* Firefox下的适配:通过内容溢出状态判断 */ @supports (scrollbar-width: auto) { .container:has(> :last-child:not(:in-range)) { padding-right: 10px; } } .item { width: 100%; background-color: green; margin-top: 5px; }
方案二:兼容旧版浏览器的 fallback 方案
如果需要兼容不支持:has()的旧浏览器,可以通过额外嵌套一层容器的方式实现:
<div class="container"> <div class="content-wrapper"> <div class="item">item1</div> <div class="item">item2</div> <div class="item">item3</div> <div class="item">item4</div> <div class="item">item5</div> </div> </div>
html { box-sizing: border-box; } *, *::before, *::after { box-sizing: inherit; } .container { overflow-y: auto; height: 70px; width: 100px; border: 1px solid red; } .content-wrapper { display: flex; flex-direction: column; padding-right: 10px; /* 无滚动条时,让wrapper宽度超出容器,抵消padding-right的影响 */ width: calc(100% + 10px); } /* 有滚动条时,wrapper宽度恢复为100%,padding-right生效 */ .container::-webkit-scrollbar:vertical { width: initial; } .container::-webkit-scrollbar:vertical ~ .content-wrapper { width: 100%; } .item { width: 100%; background-color: green; margin-top: 5px; }
这个方案通过嵌套层的宽度变化,实现了有滚动条时保留内边距、无滚动条时内容占满的效果,兼容大部分旧版浏览器。
内容的提问来源于stack exchange,提问作者AlwaysLearning
相关产品推荐
相关产品推荐

