代碼
提交代碼
<!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 { position: relative }
.center {
/* 絕對定位 */
position: absolute;
/* 上方和左方為50% */
top: 50%;
left: 50%;
/* 不用給寬高,但是可以給個內邊距防止內容與盒子過于貼合 */
padding: 10px;
/* 這個50%是相對于自身寬高而言的 */
transform: translate(-50%, -50%);
/* 白色背景 */
background: white;
}
</style>
</head>
<body>
<div class="center">
用內容撐開盒子
</div>
</body>
</html>
運行結果