史上最全垂直居中方法(almost)总结

雨点打透心脏的1/2处 2022-11-25 10:15 179阅读 0赞
  1. // HTML 结构
  2. <div class="container">
  3. <div class="center"></div>
  4. </div>
  5. // table法
  6. .container {
  7. width: 600px;
  8. height: 400px;
  9. background: #eee;
  10. display: table-cell;
  11. text-align: center;
  12. vertical-align: middle;
  13. }
  14. .center {
  15. background: tomato;
  16. }
  17. // 绝对定位法+transform(常用)
  18. .container {
  19. height: 400px;
  20. background: #eee;
  21. position: relative;
  22. }
  23. .center {
  24. background: tomato;
  25. position:absolute;
  26. top: 50%;
  27. left: 50%;
  28. transform: translate(-50%, -50%);
  29. }
  30. // flex 个人常用,有兼容性风险
  31. .container{
  32. height: 400px;
  33. background: #eee;
  34. display: flex;
  35. justify-content: center;
  36. align-items: center;
  37. }
  38. .center{
  39. width: 100px;
  40. height: 100px;
  41. background: tomato;
  42. }
  43. // 绝对定位+margin特性
  44. .container{
  45. width: 400px;
  46. height: 400px;
  47. background: gray;
  48. position: relative;
  49. }
  50. .center {
  51. position: absolute;
  52. height: 200px;
  53. width: 200px;
  54. left: 0;
  55. top: 0;
  56. bottom: 0;
  57. right: 0;
  58. margin: auto;
  59. }
  60. // grid网格法
  61. .container{
  62. display: grid;
  63. width: 300px;
  64. grid-template-columns: repeat(3, 100px);
  65. grid-template-rows: repeat(3, 100px);
  66. background: gainsboro;
  67. }
  68. .center {
  69. background: tomato;
  70. grid-column: 2 / 3;
  71. grid-row: 2 / 2;
  72. }

如果你已经看到这里,那咱们也是有缘人,老衲将收藏多年的最简方法授予你:

  1. .container {
  2. height: 400px;
  3. display: flex;
  4. }
  5. .center {
  6. margin: auto;
  7. width: 100px;
  8. height: 100px;
  9. background: tomato;
  10. }

发表评论

表情:
评论列表 (有 0 条评论,179人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ByteBuddy(

    ByteBuddy(史上最全) 文章很长,建议收藏起来慢慢读! [总目录 博客园版][Link 1] 为大家准备了更多的好文章!!!! 推荐:尼恩Java面试宝典(持