.box { display: flex; justify-content: center; /*水平居中*/ }
<div class="box"> <h1>flex彈性佈局justify-content屬性實現元素水平居中</h1> <h1>flex彈性佈局justify-content屬性實現元素水平居中</h1> <h1>flex彈性佈局justify-content屬性實現元素水平居中</h1> </div>
csscss
.box { display: flex; justify-content: center; width: 100%; background: #0099cc } h1 { font-size: 1rem; padding: 1rem; border: 1px dashed #FFF; color: #FFF; font-weight: normal; }
效果圖html
1.單個h1標籤垂直居中佈局
.box { display: flex; align-items:center; /*垂直居中*/ }
2.多個h1標籤並排垂直居中flex
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <style> .box { display: flex; width: 980px; height: 30rem; align-items: center; background: #6161d1 } h1 { font-size: 1rem; padding: 1rem; border: 1px dashed#FFF; color: #FFF } </style> <body> <div class="box"> <h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1> <h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1> <h1>flex彈性佈局justify-content屬性實現元素垂直居中</h1> </div> </body>
總結:spa
經常使用代碼:code
display: flex; align-items: center; /*垂直居中*/ justify-content:center; /*水平居中*/