css3 flex布局实现平均分配元素的示例代码
(编辑:jimmy 日期: 2024/12/28 浏览:3 次 )
本文主要介绍了css3 flex布局实现平均分配元素,给自己留个笔记,也分享给大家,具体如下:
例子一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>flex 布局</title> <style> *{ padding:0; margin:0; } body,html{ height: 100vh; min-width: 800px; } .container{ display:flex; flex-wrap:wrap; display: -webkit-flex; /* Safari */ } .container>.item{ border: 1px solid black; flex:1; height:100px; background: #abcdef; } </style> </head> <body> <div class="container"> <div class="item"></div> <main class="item"></main> <div class="item"></div> </div> </body> </html>
例子二:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>flex 布局</title> <style> *{ padding:0; margin:0; box-sizing: border-box; } body,html{ width: 100%; height: 100vh; min-width: 800px; display:flex; display: -webkit-flex; /* Safari */ justify-content: center; align-items: center; } .container{ width: 300px; height: 300px; display:flex; display: -webkit-flex; /* Safari */ flex-wrap: wrap; } .container>.item{ flex:0 0 33.3%; height:100px; background: #abcdef; border: 1px solid red; } main{ flex:0 0 33.3%; height:100px; background-color: #ccc; border: 1px solid red; } </style> </head> <body> <div class="container"> <div class="item">left</div> <main>main</main> <div class="item">right</div> <div class="item">left</div> <main>main</main> <div class="item">right</div> <div class="item">left</div> <main>main</main> <div class="item">right</div> </div> </body> </html>
flex:0 0 33.3% 相当于flex-basis:33.3%,使每一个元素的宽度占外层容器的33.3%,因此每行最多能够排开三个元素。
flex-wrap:wrap 表示每行填满时会自动换行。
例子三:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>flex 布局</title> <style> *{ padding:0; margin:0; box-sizing: border-box; } body,html{ width: 100%; height: 100vh; min-width: 800px; display:flex; display: -webkit-flex; /* Safari */ justify-content: center; align-items: center; } .container{ width: 300px; height: 300px; margin: 50px; display:flex; display: -webkit-flex; /* Safari */ flex-wrap: wrap; justify-content: space-between; } .container>.item{ flex:0 0 30%; height:90px; background: #abcdef; border: 1px solid red; } main{ flex:0 0 30%; height:90px; background-color: #ccc; border: 1px solid red; } </style> </head> <body> <div class="container"> <div class="item">left</div> <main>main</main> <div class="item">right</div> <div class="item">left</div> <main>main</main> <div class="item">right</div> <div class="item">left</div> <main>main</main> <div class="item">right</div> </div> </body> </html>
justify-content:space-between表示主轴方向的多余空间平均分配在两两item之间。
下一篇:flex布局实现上下固定中间滑动的布局方式