使用Flexbox实现高级CSS布局
CSS3提供了一种名为弹性盒布局(Flexbox)的布局模式。Flexbox(弹性盒)是CSS3的一种布局模式。使用此模式,您可以轻松创建复杂应用程序和网页的布局。它包括容器、弹性项目等。容器具有以下属性:
flex-direction
flex-wrap
flex-flow
justify-content
align-items
align-content
这是一张包含所有Flexbox示例的图片。它使用了flex、flex-wrap、justify-content、align-items等属性:
设置父容器样式
我们在这里设置了父容器的样式。通过将`display`属性设置为`flex`,使flex容器变得灵活:
.container { display: flex; flex-wrap: wrap; justify-content: space-evenly; background-color: lightblue; }
弹性项目
父容器包含三个容器,即弹性项目:
<div class="container1"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container2"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container3"> <div>1</div> <div>2</div> <div>3</div> </div>
设置弹性项目1样式
弹性项目的样式如下所示,`align-self`设置为`flex-start`,以便元素位于容器的开头:
.container1 { align-self: flex-start; display: flex; background-color: rgb(71, 30, 255); width: 200px; margin: 20px; } .container1 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; }
设置弹性项目2样式
弹性项目的样式如下所示。`justify-content`设置为`center`,以便将弹性项目与容器中心对齐:
container2 { display: flex; background-color: rgb(14, 126, 79); width: 200px; justify-content: center; align-self: flex-start; margin: 20px; } .container2 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; }
设置弹性项目3样式
弹性项目的样式如下所示。`flex-direction`设置为`column`,以便弹性项目垂直显示为列:
.container3 { display: flex; flex-direction: column; background-color: rgb(168, 60, 10); width: 200px; align-items: center; margin: 20px; } .container3 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; width: 20px; font-size: 30px; }
使用Flexbox进行CSS布局
示例
以下是使用Flexbox实现高级CSS布局的代码:
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .container { display: flex; flex-wrap: wrap; justify-content: space-evenly; background-color: lightblue; } .container1 { align-self: flex-start; display: flex; background-color: rgb(71, 30, 255); width: 200px; margin: 20px; } .container1 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; } .container2 { display: flex; background-color: rgb(14, 126, 79); width: 200px; justify-content: center; align-self: flex-start; margin: 20px; } .container2 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; font-size: 30px; } .container3 { display: flex; flex-direction: column; background-color: rgb(168, 60, 10); width: 200px; align-items: center; margin: 20px; } .container3 > div { background-color: #f1f1f1; margin: 10px; padding: 10px; width: 20px; font-size: 30px; } </style> </head> <body> <h1>Flex layout example</h1> <div class="container"> <div class="container1"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container2"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container3"> <div>1</div> <div>2</div> <div>3</div> </div> <div class="container1"> <div>1</div> <div>2</div> <div>3</div> </div> </div> </body> </html>
广告