renjie-run / blog

Personal Blog
2 stars 0 forks source link

Flex 布局下的滚动问题 #20

Open renjie-run opened 4 years ago

renjie-run commented 4 years ago

场景

通过使用 flex 的方式,来让这个元素中的子元素上下左右居中。

.father {
  width: 300px;
  height: 300px;
  margin: auto;
  border: 1px solid red;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: scroll;
}

.child {
  width: 50px;
  height: 50px;
  background-color: skyblue;
}

这种情况下效果如下,一点毛病都没有: image

但是,当子元素的高度超出了父元素的高度(宽度亦同),这里就有问题了:不能滚动到顶部!

.child {
  width: 50px;
  height: 500px;
  background-color: skyblue;
}

效果如下: image

解决方案

目前从网上查找到了一种方案。

  1. margin: auto 通过对使用了 flex 元素下的子元素使用 margin: auto 这个样式,便能解决这个问题。
    .child {
    width: 50px;
    height: 500px;
    background-color: skyblue;
    margin: auto;
    }

处理过的效果图如下: image

应该还有很多其他的解决方案,欢迎留言👏👏