1、基于flex布局
.box{ width: 300px; height: 300px; background-color: #0000ff; display: flex; justify-content: center; align-items: center; } .main{ width: 100px; height: 100px; background-color: #0e5370; } /*****或*****/ .box{ width: 300px; height: 300px; background-color: #0000ff; display: flex; } .main{ width: 100px; height: 100px; background-color: #0e5370; margin: auto; }
2、基于绝对定位
/********** 父元素设置为:position: relative; 子元素设置为:position: absolute; 距上50%,据左50%,然后减去元素自身宽度的距离就可以实现 ********************/ .box{ width: 300px; height: 300px; background-color: #0000ff; position: relative; } .main{ width: 100px; height: 100px; background-color: #0e5370; position: absolute; top: 50%; left: 50%; margin: -50px 0 0 -50px; } /*position transform 元素未知宽度 如果元素未知宽度,只需将上面例子中的margin: -50px 0 0 -50px;替换为:transform: translate(-50%,-50%);*/ .box{ width: 300px; height: 300px; background-color: #0000ff; position: relative; } .main{ width: 100px; height: 100px; background-color: #0e5370; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }
3、基于表格样式
/******* table-cell布局 因为table-cell相当与表格的td,td为行内元素,无法设置宽和高,所以嵌套一层,嵌套一层必须设置display: inline-block; ******/ .box{ width: 300px; height: 300px; background-color: #0000ff; display: table; } .main{ display: table-cell; text-align: center; vertical-align: middle; } .inner{ width: 100px; height: 100px; background-color: #0e5370; display: inline-block; }
<div class="box"> <div class="main"> <div class="inner"></div> </div> </div>
原文:https://www.cnblogs.com/wenzizaigaoge/p/10537020.html