未知大小的父元素如何实现让子元素水平垂直居中?

x33g5p2x  于2022-03-22 转载在 其他  
字(1.9k)|赞(0)|评价(0)|浏览(362)

一、写在前面
今天看到一个面试题,问未知大小的父元素如何实现让其子元素水平垂直居中。现在总结一下几种方法。
二、实现方法
2.1、flex布局

  1. <!DOCTYPE html>
  2. <html lang="cn">
  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. .parent {
  10. width: 200px;
  11. height: 200px;
  12. background-color: red;
  13. display:flex;
  14. justify-content: center;
  15. align-items: center;
  16. }
  17. </style>
  18. </head>
  19. <body>
  20. <div class="parent">
  21. <div class="child">hello world</div>
  22. </div>
  23. </body>
  24. </html>

2.2、使用table布局

  1. <!DOCTYPE html>
  2. <html lang="cn">
  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. .parent {
  10. width: 200px;
  11. height: 200px;
  12. display: table;
  13. background-color: red;
  14. }
  15. .child {
  16. display: table-cell;
  17. vertical-align: middle;
  18. text-align: center;
  19. }
  20. </style>
  21. </head>
  22. <body>
  23. <div class="parent">
  24. <div class="child">hello world</div>
  25. </div>
  26. </body>
  27. </html>

2.3、transform

  1. <!DOCTYPE html>
  2. <html lang="cn">
  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. .parent {
  10. width: 200px;
  11. height: 200px;
  12. background-color: red;
  13. position: relative;
  14. }
  15. .child {
  16. position: absolute;
  17. left: 50%;
  18. top: 50%;
  19. transform: translate(-50%, -50%);
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <div class="parent">
  25. <div class="child">hello world</div>
  26. </div>
  27. </body>
  28. </html>

2.4、

相关文章