1.文字居中
<html> <head> <title>我的第一個 HTML 頁面</title> </head> <body> <div id="father"> <span id="child"> 子元素 </span> </div> </body> <style type="text/css"> #father{ width:200px; height:100px; border:1px solid red; text-align:center; } #child{ line-height:100px; } </style>

2. div居中
<html> <head> <title>我的第一個 HTML 頁面</title> </head> <body> <div id="father"> <div id="child"> </div> </div> </body> <style type="text/css"> #father{ width:200px; height:100px; border:1px solid red; display: flex; justify-content:center; align-items: center; } #child{ width:50%; height:50%; border:1px solid blue; } </style> </html>

3. div居中
<html> <head> <title>我的第一個 HTML 頁面</title> </head> <body> <div id="father"> <div id="child"> </div> </div> </body> <style type="text/css"> #father{ width:200px; height:100px; border:1px solid red; position:relative; } #child{ width:50px; height:50px; border:1px solid blue; top:50%; left:50%; transform:translate(-50%,-50%); position:absolute; } </style> </html>

4.div
使用彈性盒子,居中變的很簡單,只想要設置 margin: auto; 可以使得彈性子元素在兩上軸方向上完全居中
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鳥教程(runoob.com)</title>
<style>
.flex-container {
display: -webkit-flex;
display: flex;
width: 400px;
height: 250px;
background-color: lightgrey;
}
.flex-item {
background-color: cornflowerblue;
width: 75px;
height: 75px;
margin: auto;
}
</style>
</head>
<body>

