移动端滑动是一个比较常见的css样式,最近也遇到了这样的效果实现,想在此写一篇博客记录一下。

横向滑动,本质就是给了一个100ml的杯子,需要你用这去装1L,2L甚至更多L的水,现实情况是多出的水会溢出来。这样的类比在开发的时候,你就能体会到,一个100px的盒子,要放置总的宽度2,300px的盒子,同理,宽度超过父元素宽度时,盒子也会溢出,那该如何做?

(1)html代码

<div class="father1">
    <div class="d1"></div>
    <div class="d2"></div>
</div>

(2)css代码

.father1 {
    width: 355px;
    height: 355px;
    background-color: aqua;
    white-space: nowrap;
    overflow-x: auto;
}

.father1::-webkit-scrollbar {
    display: none;
}

.father1 .d1 {
    width: 355px;
    height: 355px;
    background-color: bisque;
    display: inline-block;
}
.father1 .d1 {
    width: 355px;
    height: 355px;
    background-color: red;
    display: inline-block;
}

实现思路:

首先将子元素转化为行内块元素display: inline-block,这个时候可能父元素的宽度并不能全部装下这些子盒子,那么就可以给父元素加上white-space: nowrap;让他们不换行,虽然添加了这一属性,但是装不下的子盒子部分其实可能会侵占别的空间,这个时候需要指定超出盒子的部分隐藏显示:overflow-x: auto;

四部曲:(1)转换为行内块–display: inline-block
(2)不换行–white-space: nowrap
(3)超出隐藏–overflow-x: auto
(4)隐藏滚动条–
::-webkit-scrollbar {
display: none;
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐