css 实现水平内容超出容器滚动

396 阅读1分钟

html

<div class="box">
  <ul>
    <li class="item">
        <a href="javascript:;">历史版本1</a>
    </li>
    <li class="item">
        <a href="javascript:;">历史版本2</a>
    </li>
  </ul>
</div>

css

.box {
    overflow-x: auto; // 不能设置为 scroll,否则即便内容没有超出父容器,也会有滚动条
    height: 1.12rem;
    position: relative;
    -webkit-overflow-scrolling: touch;
}

.box ul {
    white-space: nowrap; // 水平不换行
    position: absolute; // 元素垂直居中
    top: 50%;
    transform: translateY(-50%);
}

.box ul li.item {
    background: #feefef;
    padding: .08rem .15rem;
    text-align: center;
    margin: 0 .15rem;
    display: inline-block; // display 为 inline-block 时,white-space: nowrap 才会起作用
}