常用css属性flex: 1详解

  • flex:1实际代表的是三个属性的简写
  • flex-grow是用来增大盒子的,比如,当父盒子的宽度大于子盒子的宽度,父盒子的剩余空间可以利用flex-grow来设置子盒子增大的占比
  • flex-shrink用来设置子盒子超过父盒子的宽度后,超出部分进行缩小的取值比例
  • flex-basis是用来设置盒子的基准宽度,并且basis和width同时存在basis会把width干掉

所以flex:1;的逻辑就是用flex-basis把width干掉,然后再用flex-grow和flex-shrink增大的增大缩小的缩小,达成最终的效果

flex-grow:1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 100px;
      background-color: hotpink;
      display: flex;
    }
 
    .box div {
      width: 100px;
    }
 
    .box div:nth-child(1) {
      flex-grow: 1;
    }
 
    .box div:nth-child(2) {
      flex-grow: 3;
    }
    .box div:nth-child(3) {
      flex-grow: 1;
    }
 
  </style>
</head>
<body>
  <div class="box">
    <div>1</div>
    <div>2</div>
    <div>3</div>
  </div>
</body>
</html>

父盒子剩余空间的200

第一个盒子扩大1/5,100+40 = 140

第二个盒子扩大3/5,100+120=220

第三个盒子扩大1/5,100+40= 140

flex-shrink:1

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 100px;
      background-color: hotpink;
      display: flex;
    }
 
    .box div {
      width: 200px;
    }
 
    .box div:nth-child(1) {
      flex-shrink: 1;
    }
 
    .box div:nth-child(2) {
      flex-shrink: 2;
    }
 
    .box div:nth-child(3) {
      flex-shrink: 1;
    }
  </style>
</head>
<body>
  <div class="box">
    <div>1</div>
    <div>2</div>
    <div>3</div>
  </div>
</body>
</html>

父盒子的宽度为500,子盒子的宽度为600,超出100,超出的100,如何进行比例缩放

第一个盒子:1/4 * 100 = 25 最终第一个盒子200-25=175
第二个盒子:2/4 * 100 = 50 最终第二个盒子200-50 = 150
第三个盒子:1/4 * 100 = 25 最终第一个盒子200-25=175

flex-basis:0%

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .box {
      width: 500px;
      height: 100px;
      background-color: hotpink;
      display: flex;
    }
 
    .box div {
      width: 100px;
    }
 
    .box div:nth-child(1) {
      flex-basis: 50px;
    }
 
    .box div:nth-child(2) {
      flex-basis: 100px;
    }
 
    .box div:nth-child(3) {
      flex-basis: 50px;
    }
  </style>
</head>
<body>
  <div class="box">
    <div>1</div>
    <div>2</div>
    <div>3</div>
  </div>
</body>
</html>

这样width的宽度就已经被flex-basis:0%干掉了

posted @ 2023-03-23 11:48  front-gl  阅读(1116)  评论(0编辑  收藏  举报