Spirit帶你了解CSS各個(gè)方向的居中方案
水平居中和垂直居中的方案
先看HTML的骨架
后面的代碼都是基于這個(gè)來寫的
- <!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>
水平居中
1. 通過 margin 水平居中
- /* 1. 通過margin 水平居中 */
- .box {
- width: 200px;
- height: 200px;
- background-color: orange;
- }
- .align {
- margin: 0 auto;
- }
2. 通過 position 和 transform 水平居中
- /* 2.通過 position 和 transform 水平居中 */
- .box {
- width: 200px;
- height: 200px;
- background-color: orange;
- }
- .align {
- position: relative;
- left: 50%;
- transform: translateX(-50%);
- }
3. 通過flex水平居中
- body {
- display: flex;
- justify-content: center;
- }
通過 text-align:center 水平居中
注意:使用text-align的時(shí)候,子元素要設(shè)置為行內(nèi)塊元素,是利用了行內(nèi)元素的特性
- body {
- text-align: center;
- }
- .box {
- display: inline-block;
- width: 200px;
- height: 200px;
- background-color: orange;
- }
垂直居中
1. flex布局垂直居中
可以在父類上加 align-item:center實(shí)現(xiàn)垂直居中
- body {
- height: 100vh;
- display: flex;
- align-items: center;
- }
也可以在子類元素上加 align-self:center 實(shí)現(xiàn)垂直居中
- .box {
- align-self: center;
- width: 200px;
- height: 200px;
- background-color: orange;
- }
通過position和transform 來垂直居中
- /* 第二種方案 position和transform */
- .vertical{
- position: relative;
- top: 50%;
- transform: translateY(-50%);
- }
絕對居中
flex布局實(shí)現(xiàn)絕對居中
- body {
- height: 100vh;
- display: flex;
- align-items: center;
- justify-content: center;
- }
通過 position和transform 實(shí)現(xiàn)絕對居中
- /* 第二種方案 position和transform */
- .box {
- position: relative;
- top: 50%;
- left: 50%;
- transform: translate(-50%, -50%);
- }