水平居中和垂直居中的方案
先看HTML的骨架
后面的代碼都是基於這個來寫的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="./style.css">
<body>
<div class="box vertical align"></div>
</body>
</html>
水平居中
-
通過 margin 水平居中
/* 1. 通過margin 水平居中 */ .box { width: 200px; height: 200px; background-color: orange; } .align { margin: 0 auto; }
-
通過 position 和 transform 水平居中
/* 2.通過 position 和 transform 水平居中 */ .box { width: 200px; height: 200px; background-color: orange; } .align { position: relative; left: 50%; transform: translateX(-50%); }
-
通過flex水平居中
body { display: flex; justify-content: center; }
-
通過 text-align:center 水平居中
注意:使用text-align的時候,子元素要設置為行內塊元素,是利用了行內元素的特性
body { text-align: center; } .box { display: inline-block; width: 200px; height: 200px; background-color: orange; }
垂直居中
-
flex布局垂直居中
可以在父類上加 align-item:center實現垂直居中
body { height: 100vh; display: flex; align-items: center; }
也可以在子類元素上加 align-self:center 實現垂直居中
.box { align-self: center; width: 200px; height: 200px; background-color: orange; }
-
通過position和transform 來垂直居中
/* 第二種方案 position和transform */ .vertical{ position: relative; top: 50%; transform: translateY(-50%); }
絕對居中
-
flex布局實現絕對居中
body { height: 100vh; display: flex; align-items: center; justify-content: center; }
-
通過 position和transform 實現絕對居中
/* 第二種方案 position和transform */ .box { position: relative; top: 50%; left: 50%; transform: translate(-50%, -50%); }