這篇文章主要是分享了三個例子( 垂直居中、響應式、聖盃 ),介紹了Flexbox的主要應用場景,並與傳統方式對比, 感覺Flexbox佈局帶來的便捷開發體驗。佈局
不使用Flexboxflex
<style> .main1 { position: relative; height: 200px; background: #8A469B; } .main1 div { display: block; width: 50%; height: 50%; background: #EA7F26; overflow: hidden; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; } .main1 div span { position: absolute; margin: 0; padding: 0; left: 50%; top: 50%; transform: translate(-50%, -50%); background: #EA7F26; } .main2 { height: 200px; display: flex; justify-content: center; align-items: center; background: #8A469B; } .main2 div { width: 50%; height: 50%; display: flex; justify-content: center; align-items: center; background: #EA7F26; } </style> <body> <h3>不使用Flexbox</h3> <div class="main1"> <div> <span> 俠課島 </span> </div> </div> <h3>使用Flexbox</h3> <div class="main2"> <div> <span> 俠課島 </span> </div> </div> </body>
使用Flexboxspa
display: flex; justify-content: center; align-items: center;
使用與否呈現的效果都是同樣的code
不使用Flexboxorm
.main { text-align: right; } .main li { display: inline-block; } /* 小於800px 大於600px */ @media screen and (max-width: 800px) { .main { text-align: justify; text-align-last: justify; } } /* 小於600px */ @media screen and (max-width: 600px) { .main li { display: block; } .main a { display: block; text-align: center; text-align-last: center; } }
使用Flexbox圖片
.main { display: flex; flex-flow: row wrap; justify-content: flex-end; } /* 小於800px 大於600px */ @media screen and (max-width: 800px) { .main { justify-content: space-between; } } /* 小於600px */ @media screen and (max-width: 600px) { .main { flex-flow: column nowrap; } }
什麼是聖盃佈局?好比下面的圖片所示:上面是一個標題、中間是左邊是目錄,中間是內容,右測是一些推薦,底部是一個版權聲明。開發
聖盃佈局和雙飛翼佈局的共同特色都是利用float+margin的負值來實現並列的結構。it
不使用Flexboxio
.left,.middle,.right { position: relative; float: left; height: 100%; } .container { padding:0 200px 0 200px; height: calc(100% - 120px); } .left { margin-left: -100%; left: -200px; width: 200px; background-color: #ffff99; } .right { margin-left: -200px; right: -200px; width: 200px; background-color: #ffff99; } .middle { width: 100%; background-color: #EE8888; word-break: break-all; } .header { height: 80px; background-color: #cdcdcd; } .footer { height: 40px; background-color: #cdcdcd; clear: both; }
使用Flexboxast
.flex { display: flex; flex-wrap: nowrap; } .leftBar { width: 200px; flex-shrink: 0; } .container { width: 100%; } .rightBar { width: 200px; flex-shrink: 0; }