首页 > 解决方案 > 停止 div 在浏览器调整大小时水平移动

问题描述

我正在尝试创建一个具有多个 div 的布局,它们的宽度和高度都相同。所有 div 的宽度为 100vw。问题是,当我调整浏览器窗口的大小时,如果最初 div 5 位于中心,它会移动,而其他一些 div 会落在中心。

我尝试使用 onresize 事件并将容器元素的 scrollLeft 更改为 container_scrollLeft = current_div_index * width_of_one_div 但这会由于对 scrollLeft 的不断操作而导致抖动行为。

.container {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-item-align: start;
  outline: none;
  -webkit-overflow-scrolling: touch;
  -ms-overflow-style: none;
  overflow-x: scroll;
  overflow-y: hidden;
  overflow-y: -moz-hidden-unscrollable;
  width: 100%;
}

.page {
  align-items: center;
  display: flex;
  height: 100%;
  justify-content: center;
  min-width: 100%;
  position: relative;
  width: 100vw;
  box-shadow: inset 0 0 20px #000000;
}
<div class="container" style="height: 400px;">
  <div class="page">
    <h1>1</h1>
  </div>
  <div class="page">
    <h1>2</h1>
  </div>
  <div class="page">
    <h1>3</h1>
  </div>
  <div class="page">
    <h1>4</h1>
  </div>
  <div class="page">
    <h1>5</h1>
  </div>
  <div class="page">
    <h1>6</h1>
  </div>
  <div class="page">
    <h1>7</h1>
  </div>
  <div class="page">
    <h1>8</h1>
  </div>
  <div class="page">
    <h1>9</h1>
  </div>
  <div class="page">
    <h1>10</h1>
  </div>
</div>

我最好寻找纯 CSS 解决方案。但是,我也欢迎基于 javascript 的解决方案。

标签: javascripthtmlcss

解决方案


推荐阅读