欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 美景 > 水平垂直居中的几种方法(总结)

水平垂直居中的几种方法(总结)

2024/10/24 11:19:41 来源:https://blog.csdn.net/weixin_51943308/article/details/142131960  浏览:    关键词:水平垂直居中的几种方法(总结)
  1. 1.使用 flexbox 的 justify-content 和 align-items

  2. .parent {display: flex;justify-content: center;  /* 水平居中 */align-items: center;      /* 垂直居中 */height: 100vh;            /* 需要指定高度 */
    }
    

  3. 2.使用 grid 的 place-items: center

  4. .parent {display: grid;place-items: center;  /* 水平和垂直同时居中 */height: 100vh;
    }
    

  5. 3.使用 position: absolute 和 transform

  6. .parent {position: relative;height: 100vh;
    }.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);
    }
    

  7. 4.使用 table-cell 和 vertical-align: middle

  8. .parent {display: table;width: 100%;height: 100vh;text-align: center;          /* 水平居中 */
    }.child {display: table-cell;vertical-align: middle;      /* 垂直居中 */
    }
    

    PS:基本没用过,这个太老了

  9. 5.使用 margin: auto(子元素固定宽高)

  10. .parent {display: block;height: 100vh;
    }.child {width: 200px;height: 200px;margin: auto;
    }
    

  11. 6.使用 line-height 和 text-align: center(仅限单行文本)

  12. .parent {height: 100vh;line-height: 100vh;  /* 行高等于容器高度 */text-align: center;  /* 水平居中 */
    }.child {display: inline-block;vertical-align: middle;
    }
    

  13. 7.使用 inline-block 和 text-align: center

  14. .parent {text-align: center;   /* 水平居中 */height: 100vh;
    }.child {display: inline-block;vertical-align: middle;  /* 垂直居中 */margin: auto;
    }
    

  15. 8.使用 min-height 和 min-width + flexbox

  16. .parent {display: flex;justify-content: center; /* 水平居中 */align-items: center;     /* 垂直居中 */min-height: 100vh;
    }.child {min-width: 200px;min-height: 200px;
    }
    

  17. 9.使用 vh 单位

  18. .parent {height: 100vh;display: flex;justify-content: center;  /* 水平居中 */align-items: center;      /* 垂直居中 */
    }
    

  19. 10.使用 absolute + display: flex(嵌套居中)

  20. .parent {position: relative;height: 100vh;
    }.child {position: absolute;top: 50%;left: 50%;transform: translate(-50%, -50%);display: flex;justify-content: center;align-items: center;
    }
    

  21. 11.使用 display: block 和 margin: auto(适用于固定宽高的元素)

  22. .parent {display: block;height: 100vh;
    }.child {width: 200px;height: 200px;margin: auto;
    }
    

  23. 12.使用 text-indent 和 white-space: nowrap(适用于文字)

  24. .parent {text-align: justify;white-space: nowrap;text-indent: 50%;transform: translateX(-50%);height: 100vh;
    }
    

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com