行內塊元素實現單列布局
1. 前言
利用元素的行內元素特性我們可以很輕松的做到水平居中。
行內塊的語法格式也很簡單:display: inline-block;
。
2. 實例代碼
<!DOCTYPE html>
<html>
<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 {
/* 令子元素水平居中 */
text-align: center;
/* 灰色背景 */
background: gray;
}
.center {
/* 令其顯示為行內塊元素 */
display: inline-block;
/* 給個寬高方便查看 */
width: 90%;
height: 100%;
/* 白色背景 */
background: white;
}
</style>
</head>
<body>
<div class="center"></div>
</body>
</html>
運行結果:
3. 小結
display: inline-block; 可以讓元素既擁有行內元素的特性,同時又擁有塊級元素的特性。
不過看了這么多種方式的單列布局,可是看起來依然還是很抽象。
換句話說就是不好看,那么下一小節我們就為其添油加醋一下,使其看起來更加貼合實際。