html结构:
<div class="main"> <div class="content"></div> </div>
一. 子元素绝对定位,left和top都设置为50%,再设置margin-left和margin-top为-1/2宽度、-1/2高度。此种情况适用于宽度高度固定的情况
.main { width: 400px; height: 400px; background: #eee; position: relative; } .content { background: #ccc; width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; margin-left: -100px; margin-top: -100px; }
二. transform,原理同方法一,此种方法可用于宽度高度不固定的情况
.main { width: 400px; height: 400px; background: #eee; position: relative; } .content { background: #ccc; width: 200px; height: 200px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
三. flex布局,父元素设置两条轴上居中对齐方式
.main { width: 400px; height: 400px; background: #eee; display: flex; justify-content: center; align-items: center; } .content { background: #ccc; width: 200px; height: 200px; display: inline-block; }
此外,设置文字垂直对齐还可以使用line-height=父元素高度、table-cell方式。使用table-cell需要设置父元素display:table
.main { width: 400px; height: 400px; background: #eee; display: table; } .content { background: #ccc; width: 200px; height: 200px; display: table-cell; vertical-align: middle; }