【问题标题】:Why scroll hides some elements when it's container have full width?为什么当容器具有全宽时滚动隐藏一些元素?
【发布时间】:2020-10-09 00:03:28
【问题描述】:

我有一个宽度为 100vw 的 div,可以使用动态元素滚动。但是,一旦您添加更多项目,第一个项目会突然消失一次,即使您尝试滚动也看不到。

这在手机上更可测试,一旦视图宽度更小。

我的问题是:如何实现自然滚动,所有项目都可见,视图宽度为 100vw?

html, body {
  height: 100vh;
  width: 100vw;
}

#images {
  overflow-x: scroll;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 35vh;
  width: 100vw;

  img {
    height: 20vh;
    width: 20vh;
    margin-right: 1.5rem;
    cursor: pointer;
  }
}
const App: React.FC = () => {
  const [photos, setPhotos] = React.useState<string[]>([])
  
  React.useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/photos')
      .then(res => res.json())
      .then(data => data && setPhotos(data.filter(p => p.id < 11).map(p => p.url)))
  }, [])
  
  return (
    <div id='images'>
      {photos.length && photos.map((p, i) => (
        <img key={`${i}${p}`} src={p} alt='mock'/>
      ))}
    </div>
  )
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.querySelector('#root')
);

密码笔:https://codepen.io/mdsp9070/full/bGeGXyg

【问题讨论】:

  • 100vw 为您提供包括滚动条宽度在内的视口宽度。所以 ClientWidth 小于 100vw。

标签: javascript html css reactjs image


【解决方案1】:

这是什么意思? Flex wrap 或 grid 会给你这个效果。

  html, body {
  height: 100vh;
  width: 100vw;
}

#images {
  overflow-x: scroll;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: center;
  width: 100vw;

  img {
    height: 20vh;
    width: 20vh;
    margin-right: 1.5rem;
    cursor: pointer;
    margin-bottom: 12px;
  }
}

编辑*

html, body {
  height: 100vh;
  width: 100%;
  box-sizing: border-box;
}

#images {
  margin: 0 auto;
  padding: 0 5px;
  box-sizing: border-box;
  overflow-x: scroll;
  display: flex;
  align-items: center;
  height: 35vh;
  width: 100%;

  img {
    box-sizing: border-box;
    height: 20vh;
    width: 20vh;
    margin-right: 1.5rem;
    cursor: pointer;
  }
}

【讨论】:

  • 所以...我还需要所有元素都在同一行
  • 这将为您提供可滚动的 div。根据我的经验,使用vw 作为主容器外的宽度单位是一种混乱的方式。你真的应该为盒子定义像素 (#image img) 并使用 100% 告诉 flex-box 在其容器/包装器空间内获取所有可用的空间。在编辑中,我删除了 justify 内容中心,因为 flex-box 会覆盖很多 css 来满足自己,并且通常会导致设计中断。希望这会有所帮助。
  • 谢谢!这解决了!我被困在这大约 1 周!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多