CSS实现水平垂直居中
<div class="wrapper"> <div class="content"></div> </div> 一、水平居中 行内元素:对其父元素应用text-align:center属性 .wrapper{ text-align: center; } 块级元素:对自身应用margin:auto属性 .content{ width: 200px; margin: 0 auto; } 二、水平垂直居中 元素固定尺寸 一般 .content{ width: 400px; height: 200px; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -200px; } 使用calc() .content{ width: 400px; height: 200px; position: absolute; top: calc(50% - 100px); left: calc(50% - 200px); } 元素尺寸由内容决定 绝对定位 .content{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } [注意] 当居中元素的高度超过了视口,则它的顶部会被视口裁切掉 在某些浏览器中