css
主页 > 网页 > css >

flex布局子元素宽度超出父元素问题及解决方案

2024-02-23 | 佚名 | 点击:

1. 第一次遇到这个问题的场景

先看效果图,大家可以看一下下面的样式,很明显左边和右边的盒子我是给的定宽,但是被挤压了
这个是我在项目中遇到的一个bug,使用的 flex 布局,由于我动态的修改绿色盒子的显示与隐藏,导致两边盒子的挤压

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<style>

.container {

  width: 1400px;

  display: flex;

  height: 100vh;

}

.box1 {

  background-color: red;

  width: 300px;

}

.box2 {

  background-color: yellow;

  flex: 1;

}

.box3 {

  background-color: green;

  width: 400px;

}

</style>

<div class="container">

  <div class="box1"></div>

  <div class="box2">

    <div>

      ...el-table

    </div>

  </div>

  <div class="box3 none"></div>

</div>

2. 第二种情况

很明显,红色的盒子没有300px

在这里插入图片描述

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<style>

  .container {

    display: flex;

    width: 600px;

    height: 600px;

  }

  .box1 {

    background-color: red;

    width: 300px;

  }

  .box2 {

    background-color: yellow;

    flex: 1;

  }

</style>

<div class="container">

  <div class="box1"></div>

  <div class="box2">Loremipsumdolorsitametconsecteturadipisicingelit.Quasi,eveniet?</div>

</div>

3. 问题原因

4. 解决方案

4.1 方案一

4.2 方案二

原文链接:
相关文章
最新更新