当前位置:   article > 正文

CSS居中对齐 (水平垂直居中对齐)

CSS居中对齐 (水平垂直居中对齐)

 

方案一:flex布局【推荐】

给容器添加样式

  1. display: flex;
  2. justify-content: center;
  3. align-items: center;

 

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <style>
  8. .box {
  9. display: flex;
  10. justify-content: center;
  11. align-items: center;
  12. border: 1px solid gray;
  13. width: 200px;
  14. height: 100px;
  15. }
  16. .item {
  17. width: 50px;
  18. height: 50px;
  19. background-color: yellow;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="box">
  25. <span class="item">水平垂直居中</span>
  26. </div>
  27. </body>
  28. </html>

方案二:子绝父相 + transform (CSS3)

限制条件:浏览器需支持CSS3,比较老的浏览器不适用
给容器(父元素)添加样式

position: relative


给内部元素添加样式

  1. position: absolute;
  2. top: 50%;
  3. left: 50%;
  4. transform: translate(-50%, -50%);

方案三:子绝父相 + 自动外边距(指定高度和宽度)

给容器(父元素)添加样式

position: relative

给内部元素添加样式

  1. position: absolute;
  2. top: 0;
  3. bottom: 0;
  4. left: 0;
  5. right: 0;
  6. margin: auto;

 方案四:子绝父相 + 负外边距 (知道宽度和高度 + 宽度和高度计算)不推荐

限制条件:需知道内部元素的宽度和高度
给容器(父元素)添加样式 

position: relative

给内部元素添加样式

  1. position: absolute;
  2. left:50%;
  3. margin-left:-内部元素宽度的一半;
  4. top: 50%;
  5. margin-top: -内部元素高度的一半;
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <style>
  8. .box {
  9. margin: 30px 30px 0px 300px;
  10. border: 1px solid gray;
  11. height: 100px;
  12. position: relative;
  13. }
  14. .item {
  15. background-color: yellow;
  16. position: absolute;
  17. left: 50%;
  18. margin-left: -150px;
  19. top: 50%;
  20. margin-top: -25px;
  21. width: 300px;
  22. height: 50px;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div class="box">
  28. <span class="item">水平垂直居中 -- 子绝父相 + 负外边距</span>
  29. </div>
  30. </body>
  31. </html>

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/241860
推荐阅读
相关标签
  

闽ICP备14008679号