Spirit带你了解CSS各个方向的居中方案

 [[425798]]

水平居中和垂直居中的方案

先看HTML的骨架

后面的代码都是基于这个来写的

 
 
 
  1. <!DOCTYPE html> 
  2. <html lang="en"
  3.  
  4. <head> 
  5.     <meta charset="UTF-8"
  6.     <meta http-equiv="X-UA-Compatible" content="IE=edge"
  7.     <meta name="viewport" content="width=device-width, initial-scale=1.0"
  8.     <title>Document</title> 
  9. </head> 
  10. <link rel="stylesheet" href="./style.css"
  11.  
  12. <body> 
  13.     <div class="box vertical align"></div> 
  14. </body> 
  15. </html> 

水平居中

1. 通过 margin 水平居中

 
 
 
  1. /* 1. 通过margin 水平居中 */ 
  2. .box { 
  3.     width: 200px; 
  4.     height: 200px; 
  5.     background-color: orange; 
  6. .align { 
  7.     margin: 0 auto; 

2. 通过 position 和 transform 水平居中

 
 
 
  1. /* 2.通过 position 和 transform 水平居中 */ 
  2. .box { 
  3.     width: 200px; 
  4.     height: 200px; 
  5.     background-color: orange; 
  6. .align { 
  7.     position: relative; 
  8.     left: 50%; 
  9.     transform: translateX(-50%); 

3. 通过flex水平居中

 
 
 
  1. body {  
  2.  
  3.     display: flex;  
  4.     justify-content: center;  
  5. }  

通过 text-align:center 水平居中

注意:使用text-align的时候,子元素要设置为行内块元素,是利用了行内元素的特性

 
 
 
  1. body { 
  2.     text-align: center; 
  3. .box { 
  4.     display: inline-block; 
  5.     width: 200px; 
  6.     height: 200px; 
  7.     background-color: orange; 

垂直居中

1. flex布局垂直居中

可以在父类上加 align-item:center实现垂直居中

 
 
 
  1. body { 
  2.     height: 100vh; 
  3.     display: flex; 
  4.     align-items: center; 

也可以在子类元素上加 align-self:center 实现垂直居中

 
 
 
  1. .box { 
  2.     align-self: center; 
  3.     width: 200px; 
  4.     height: 200px; 
  5.     background-color: orange; 

通过position和transform 来垂直居中

 
 
 
  1. /* 第二种方案 position和transform */ 
  2. .vertical{ 
  3.     position: relative; 
  4.     top: 50%; 
  5.     transform: translateY(-50%); 

绝对居中

flex布局实现绝对居中

 
 
 
  1. body { 
  2.     height: 100vh; 
  3.     display: flex; 
  4.     align-items: center; 
  5.     justify-content: center; 

通过 position和transform 实现绝对居中

 
 
 
  1. /* 第二种方案 position和transform */ 
  2. .box { 
  3.     position: relative; 
  4.     top: 50%; 
  5.     left: 50%; 
  6.     transform: translate(-50%, -50%); 

 

THE END