元素使用 align-items center 和 overflow auto 之后,部分内容显示不全

当我们为了让内容居中使用了 align-items center 属性之后,因为屏幕小的会遮挡一部分内容

我们就会给盒子再加上 overflow-y auto 这个属性

但是当我们缩小屏幕时,会发现,内容的上半部分会显示不出来

<style>
  .box {
    height: 100vh;
    display: flex;
    align-items: center;
    overflow-y: auto;
  }

  .content {
    height: 600px;
  }
</style>
<body>
  <div class="box">
    <div class="content"></div>
  </div>
</body>

 这是因为元素在侧轴居中。如果元素在侧轴上的高度高于其容器,那么在两个方向上溢出距离相同

参考文档:

align-items - CSS(层叠样式表) | MDN

这里提供两种解决方案:

1. 嵌套一层盒子

<style>
  .container {
    height: 100vh;
    display: flex;
    align-items: center;
    overflow-y: auto;
  }
  .box {
    height: 100%;
  }

  .content {
    height: 600px;
  }
</style>
<body>
  <div class="container">
    <div class="box">
      <div class="content"></div>
    </div>
  </div>
</body>

2. 将 display flex 改为 display grid

<style>
  .box {
    height: 100vh;
    display: grid;
    align-items: center;
    overflow-y: auto;
  }

  .content {
    height: 600px;
  }
</style>
<body>
  <div class="box">
    <div class="content"></div>
  </div>
</body>

======================这里写一些废话,不用看

因为 csdn 假装自己很了解文章质量

你写的少就是质量差的文章,它不会往上给你推,就很搞笑

csdn 新加的质量检测功能,真的6,“ yyds ”

扫描二维码关注公众号,回复: 15903820 查看本文章

我相信遇到这个问题,我的答案可以解决 100% 的问题,你说我的文章质量不够?

难道要让我写很多废话在文章里吗?

猜你喜欢

转载自blog.csdn.net/weixin_42335036/article/details/125515255