You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

87 lines
2.7 KiB

2 years ago
  1. <html lang="en">
  2. <head>
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <style>
  8. #div0 {
  9. display: flex;
  10. width: 400px;
  11. height: 500px;
  12. background-color: aqua;
  13. }
  14. #div0 div {
  15. width: 200px;
  16. height: 200px;
  17. background-color: blue;
  18. /* flex-basis 属性用于设置或检索弹性盒伸缩基准值(就是设置子元素的宽度),上面的 width 将失效 */
  19. /* flex-basis: 30%; 30% 是父元素宽度的 30% ,也可以使用 px、rem */
  20. }
  21. #div0 div:nth-child(1) {
  22. flex-basis: 50px;
  23. /* flex-grow 属性用于设置或检索弹性盒子的扩展比率 */
  24. /* 计算过程:
  25. 父元素宽度 - 第一个子元素宽度 - 第二个子元素宽度 400 - 50 - 100 = 250px
  26. 再将剩余的 250px 的宽度 除以 总份数(全部子元素的份数),因为第一个和第二个子元素都设置了 flex-grow: 1 ,表示每个子元素占一份,总共 2 份
  27. 250 / 2 = 125 每份为 125 px
  28. 再将子元素的宽度 + 占比份数 x 每份宽度(1 x 125, 如果是两份就是 2 x 125)
  29. 第一个子元素宽度: 50 + 125 = 175
  30. 第二个子元素宽度: 100 + 125 = 225
  31. */
  32. flex-grow: 1;
  33. }
  34. #div0 div:nth-child(2) {
  35. flex-basis: 100px;
  36. flex-grow: 1;
  37. }
  38. #div1 {
  39. display: flex;
  40. margin-top: 50px;
  41. width: 400px;
  42. height: 500px;
  43. background-color: aqua;
  44. }
  45. #div1 div {
  46. width: 200px;
  47. height: 200px;
  48. background-color: blue;
  49. }
  50. #div1 div:nth-child(1) {
  51. flex-basis: 300px;
  52. /* flex-shrink 是设置弹性盒子的缩小比率 */
  53. /* 计算过程跟 flex-grow 一样
  54. 计算超出部分:父元素宽度 - 所有子元素宽度 400 - 300 - 300 = -200
  55. 超出部分 / 所有子元素份数的总和 200 / 4 = 50
  56. 第一个子元素:300 - 50 x 1 = 250
  57. 第二个子元素:300 - 50 x 3 = 150
  58. */
  59. flex-shrink: 1;
  60. }
  61. #div1 div:nth-child(2) {
  62. flex-basis: 300px;
  63. flex-shrink: 3;
  64. }
  65. </style>
  66. </head>
  67. <body>
  68. <div id="div0">
  69. <div>1</div>
  70. <div>2</div>
  71. </div>
  72. <div id="div1">
  73. <div>3</div>
  74. <div>4</div>
  75. </div>
  76. </body>
  77. </html>