本文是从简书复制的, markdown语法可能有些出入, 想看"正版"和更多内容请关注 简书: 小贤笔记

情况一: 父子容器宽高已知

方法一

  • html
<div class="father">
<div class="son"></div>
</div>
  • css
.father {
position: relative;
width: 1000px;
height: 600px;
background: lightblue;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
top: 50%;
margin-top: -50px; /* 高度的一半 */
left: 50%;
margin-left: -50px; /* 宽度的一半 */
}

方法二

利用 margin: auto; 自动分配多余空间

  • html
<div class="father">
<div class="son"></div>
</div>
  • css
.father {
position: relative;
width: 1000px;
height: 600px;
background: lightblue;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}

top、left、right、bottom 的值相等即可,不一定要都是0

方法三

用 Flex 布局

  • html
<div class="father">
<div class="son"></div>
</div>
  • css
.father {
width: 1000px;
height: 600px;
background: lightblue;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.son {
width: 100px;
height: 100px;
background: yellow;
}

情况二: 父子容器宽高未知

方法一

  • html
<div class="father">
<div class="son"></div>
</div>
  • css
.father {
position: relative;
width: 1000px;
height: 600px;
background: lightblue;
}
.son {
position: absolute;
width: 100px;
height: 100px;
background: yellow;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

方法二

用 Flex 布局

  • html
<div class="father">
<div class="son"></div>
</div>
  • css
.father {
width: 1000px;
height: 600px;
background: lightblue;
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.son {
width: 100px;
height: 100px;
background: yellow;
}

还有其他方法的小伙伴们欢迎补充 谢谢!

最新文章

  1. sql-ASCII函数运用
  2. 【Linux】将Oracle安装目录从根目录下迁移到逻辑卷
  3. linux 增加用户 useradd 用法小结及配置文件说明
  4. 使用ODP.NET一次执行多句SQL语句
  5. 软工实践个人练习-使用github进行代码管理
  6. [读书笔记]算法(Sedgewick著)&#183;第一章(1)
  7. 读书笔记 effective c++ Item 27 尽量少使用转型(casting)
  8. Go语言备忘录:基本数据结构
  9. 使用paramiko远程执行
  10. vue 如何点击按钮返回上一页
  11. sourceTree如何不用注册就使用
  12. si_da
  13. Python 第三方库 cp27、cp35 等文件名的含义(转)
  14. Northwind学习笔记
  15. Pytorch 各种奇葩古怪的使用方法
  16. vc6中向vs2010迁移的几个问题(2)
  17. Jackson 处理复杂类型(List,map)两种方法
  18. Hadoop提交作业流程
  19. ruby中的预定义变量(Predifined Variables)
  20. Java 的Integer、int与new Integer到底怎么回事?

热门文章

  1. c++11 enable_shared_from_this
  2. [转] watch 命令使用(linux监控状态)
  3. 使用try-with-resource遇到的问题
  4. Docker 镜像加速
  5. spring.net AOP
  6. 那些H5用到的技术(3)——屏幕场景滑动
  7. 8、在Shell脚本中使用函数
  8. Wordpress 忘记密码怎么办?
  9. jenkins启动脚本
  10. 在Android下通过ExifInterface类操作图片的Exif信息