css盒子水平垂直居中的几种方式
第一种:son盒子中定位的上下左右全部为0,然后margin:auto
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 <style> 9 *{ 10 margin: 0; 11 padding: 0; 12 } 13 .box{ 14 position: relative; 15 width: 500px; 16 height: 500px; 17 background-color: antiquewhite; 18 } 19 .son{ 20 position: absolute; 21 top: 0; 22 right: 0; 23 bottom: 0; 24 left: 0; 25 margin: auto; 26 width: 200px; 27 height: 200px; 28 background-color: skyblue; 29 } 30 </style> 31 </head> 32 <body> 33 <div class="box"> 34 <div class="son"></div> 35 </div> 36 </body> 37 </html>
第二种:top50%,left50%,然后使用transform: translate(-50%,-50%); ***我最常用的
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 <style> 9 *{ 10 margin: 0; 11 padding: 0; 12 } 13 .box{ 14 position: relative; 15 width: 500px; 16 height: 500px; 17 background-color: antiquewhite; 18 } 19 .son{ 20 position: absolute; 21 top: 50%; 22 left: 50%; 23 transform: translate(-50%,-50%); 24 width: 200px; 25 height: 200px; 26 background-color: skyblue; 27 } 28 </style> 29 </head> 30 <body> 31 <div class="box"> 32 <div class="son"></div> 33 </div> 34 </body> 35 </html>
第三种
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 6 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 7 <title>Document</title> 8 <style> 9 *{ 10 margin: 0; 11 padding: 0; 12 } 13 .box{ 14 position: relative; 15 width: 500px; 16 height: 500px; 17 background-color: antiquewhite; 18 } 19 .son{ 20 position: absolute; 21 top: 50%; 22 left: 50%; 23 margin: -100px -100px; 24 width: 200px; 25 height: 200px; 26 background-color: skyblue; 27 } 28 </style> 29 </head> 30 <body> 31 <div class="box"> 32 <div class="son"></div> 33 </div> 34 </body> 35 </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构