彈性布局實現單列布局
1. 前言
彈性布局已經成為移動端最流行的布局方式之一了,還不了解的同學趕快去了解一下吧!本節我們就以彈性布局的方式實現單列布局。
2. 實例代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 清除默認樣式 */
* { padding: 0; margin: 0; }
/* 令html和body全屏顯示, 并有一個灰色背景 */
html, body { height: 100%; background: gray; }
/* 找到單列盒子的直接父元素 */
body {
/* 令其變成彈性布局 */
display: flex;
/* 水平方向居中 */
justify-content: center;
}
.center {
/* 相當于flex版的width: 90% */
flex-basis: 90%;
/* 白色背景 */
background: white;
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
運行結果:
3. 小結
如果對彈性盒子不太了解的直接記住這幾個要點即可:
- 父元素設置 display: flex;
- 水平方向屬性為 justify-content;
- 垂直方向屬性為 align-items;
下一小節我們來講一下絕對定位 + 平移來實現單列布局。