美文网首页
解决使用flex布局,当子元素内容超出父元素时,不出现滚动条的问

解决使用flex布局,当子元素内容超出父元素时,不出现滚动条的问

作者: 狂奔的胖蜗牛 | 来源:发表于2023-05-30 18:40 被阅读0次

需求

最近有个需求,就是有一个div,宽高是固定的,内部的元素呢,使用flex横向布局,一开始,当内部的元素比较少的时候,flex布局是能够正常显示的,如下图


image.png

其中,绿色的是父元素,橙色的是内部的元素。简单的代码如下,为了方便说明,把css样式写成了内联样式。

<div
      style="
        height: 100px;
        width: 400px;
        background-color: green;
        display: flex;
        overflow-y: auto;
      "
    >
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
        "
      ></div>
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
        "
      ></div>
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
        "
      ></div>
    </div>

看起来是没有问题的,但是当内部元素过多时,问题出现了。


image.png

这完全不是我想要的效果,我想要的是超出父元素后,出现滚动条,而不是把子元素压缩了。

解决办法

解决办法很简单,默认情况下,flex布局有一个属性flex-shrink,指定了当出现压缩时,元素被压缩的比例。默认值是1,所以上面的问题就是由于该属性引起的,默认情况下所有的子元素都被压缩了。我们只要把子元素的flex-shrink设置成0即可。代码如下

<div
      style="
        height: 100px;
        width: 400px;
        background-color: green;
        display: flex;
        overflow-y: auto;
      "
    >
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
          flex-shrink: 0;
        "
      ></div>
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
          flex-shrink: 0;
        "
      ></div>
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
          flex-shrink: 0;
        "
      ></div>
      <div
        style="
          height: 100px;
          width: 100px;
          background-color: orange;
          border: 1px solid white;
          flex-shrink: 0;
        "
      ></div>
      ......
    </div>

最终结果满足了我的需求。


image.png

相关文章

网友评论

      本文标题:解决使用flex布局,当子元素内容超出父元素时,不出现滚动条的问

      本文链接:https://www.haomeiwen.com/subject/jnreedtx.html