面试题面试题面试题之css(四)
2ChaosFlex 布局
Flex 布局是 CSS3 中的一种布局方式,它通过简化布局的实现过程,极大地增强了 CSS 布局的能力。使用 Flex 布局可以轻松地创建各种复杂的布局。
Flex 容器与项目
- Flex 容器:设置了
display: flex 或 display: inline-flex 的元素。
- Flex 项目:容器内部的子元素。
常见的 Flex 属性
容器属性
display:指定为 Flex 容器。
1 2 3
| .container { display: flex; }
|
flex-direction:定义主轴方向。
1 2 3
| .container { flex-direction: row; }
|
justify-content:定义主轴上的对齐方式。
1 2 3
| .container { justify-content: center; }
|
align-items:定义交叉轴上的对齐方式。
1 2 3
| .container { align-items: center; }
|
flex-wrap:定义是否换行。
1 2 3
| .container { flex-wrap: nowrap; }
|
项目属性
flex:指定项目如何分配空间。
align-self:允许单个项目有不同的对齐方式。
1 2 3
| .item { align-self: center; }
|
使用 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
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Flex布局居中</title> <style> .container { display: flex; justify-content: center; align-items: center; height: 100vh; border: 1px solid #000; } .item { width: 100px; height: 100px; background-color: lightcoral; } </style> </head> <body> <div class="container"> <div class="item">居中</div> </div> </body> </html>
|
使用 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 29 30
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Flex布局两栏</title> <style> .container { display: flex; } .left, .right { flex: 1; height: 100vh; } .left { background-color: lightblue; } .right { background-color: lightgreen; } </style> </head> <body> <div class="container"> <div class="left">左侧栏</div> <div class="right">右侧栏</div> </div> </body> </html>
|
使用 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 29 30 31 32 33 34 35
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Flex布局三栏</title> <style> .container { display: flex; } .left, .middle, .right { flex: 1; height: 100vh; } .left { background-color: lightblue; } .middle { background-color: lightcoral; } .right { background-color: lightgreen; } </style> </head> <body> <div class="container"> <div class="left">左侧栏</div> <div class="middle">中间栏</div> <div class="right">右侧栏</div> </div> </body> </html>
|