今天总结一下我所遇到过的 让一个元素水平居中的方式
<!--* @Author: HuKang* @Date: 2023-09-19 11:07:44* @LastEditTime: 2023-12-22 22:52:38* @LastEditors: HuKang* @Description: * @FilePath: \route-planning\tempDemo.html
-->
<!DOCTYPE html>
<html>
<head><title>右键菜单栏示例</title></head>
<body><div class="father"><div class="children"></div></div>
</body>
</html>
文章目录
- 1. 定位 + margin
- 2. 定位 + transform
- 3. flex
- 4. grid 布局
- 5. table 布局
1. 定位 + margin
<style>*{margin: 0;padding: 0;}.father{width: 400px;height: 400px;border: 1px solid;position: relative;}.children{width: 200px;height: 200px;background-color: pink;position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto;}
</style>
2. 定位 + transform
<style>*{margin: 0;padding: 0;}.father{width: 400px;height: 400px;border: 1px solid;position: relative;}.children{width: 200px;height: 200px;background-color: red;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);}
</style>
3. flex
<style>*{margin: 0;padding: 0;}.father{width: 400px;height: 400px;border: 1px solid;display: flex;justify-content: center;align-items: center}.children{width: 200px;height: 200px;background-color: red;}</style>
4. grid 布局
5. table 布局
参考:https://zhuhukang.blog.csdn.net/article/details/128366937