水平居中
行内元素
为父元素设置中’text-align:center’样式<div style="text-align: center"> <span>行内元素水平居中</span> </div>
定宽块级元素
定义元素左右margin为auto<div> <div style="width: 100px;height: 100px;background-color: green;margin: 0 auto"> </div> </div>
不定宽块级元素
a. 将块级元素加入<table>
标签
例如:<table style="margin: 0 auto"> <tbody> <tr><td> <div>设置table实现水平居中</div> </td></tr> </tbody> </table>
b. 设置块级元素样式
display:inline
,然后再为父元素添加text-align:center
样式
例如:<div style="text-align: center"> <div style="display: inline"> 设置inline实现水平居中 </div> </div>
c. 在块级元素外加一层父元素,并设置父元素样式为
style="float:left;position:relative;left:50%"
;设置块级元素样式为style="float:left;position:relative;left:-50%"
例如:<div style="float:left;position:relative;left: 50%"> <div style="position: relative;left: -50%"> 设置relative实现水平居中 </div> </div>
垂直居中
父元素高度确定的单行文本
将父元素height与line-height设置为相同值
例如:<div style="height: 100px;line-height: 100px"> 设置行高实现垂直居中 </div>
父元素高度确定的多行文本
a. 使用<table>
标签<table> <tbody> <tr><td style="height:40px;width:200px;background:#ccc"> <div> <p style="text-align:center">设置table实现垂直居中</p> <p style="text-align:center">设置table实现垂直居中</p> </div> </td></tr> </tbody> </table>
b. 为块级元素添加
display:table-cell;
样式,并设置vertical-align:middle
<div style="width: 200px;display: table-cell;height: 200px;vertical-align: middle;background-color: #cccccc"> <p>设置table-cell实现垂直居中</p> <p>设置table-cell实现垂直居中</p> </div>
c. 任意元素设置垂直居中
/*要垂直居中的元素*/ .middle{ position:absolute; transform:translateY(50%); } /*垂直居中元素的父元素*/ .parent{ position:relative; }