首先是水平居中,最简单的办法当然就是
margin:0 auto;
垂直居中利用line-height
.wrap{ line-height: 200px;/*垂直居中关键*/ text-align:center; height: 200px; font-size: 36px; background-color: #ccc; }
利用padding和background-clip配合实现p的水平垂直居中:
<p class="parent"> <p class="children"></p> </p>
.parent{ margin:0 auto; width:200px; height:200px; background-color:red; } .children { width: 100px; height: 100px; padding: 50px; background-color: black; background-clip:content-box;/*居中的关键*/
margin填充水平垂直居中
<p class="parent"> <p class="children"></p> </p>
@parentWidth:200px; @childrenWidth:50px; .parent { margin:0 auto; height:@parentWidth; width:@parentWidth; background: red; overflow:hidden;/*触发BFC*/ } .children { height:@childrenWidth; width:@childrenWidth; margin-left:auto; margin-right:auto; margin-top: (@parentWidth - @childrenWidth) / 2; background:black; }
absolute定位水平居中
<p class="parent"> <p class="children"></p> </p>
.parent { position:relative; margin:0 auto; width:200px; height:200px; background-color:red; } .children { position:absolute; left:50%; top:50%; margin:-25px 0 0 -25px ; height:50px; width:50px; background-color: black; }
text-align居中
.parent { text-align:center; margin:0 auto; width:200px; height:200px; background:red; } .children { positiona;absolute; margin-top:75px; width:50px; height:50px; background: black; display:inline-block;/*使其父元素text-align生效*/ }
transform居中
<p class="parent"> <p class="children"> <p class="children-inline">我是水平垂直居中噢!</p> </p> </p>
.parent { float: left; width: 100%; height: 200px; background-color: red; } .children { float:left; position:relative; top:50%; left:50%; } .children-inline { position: relative; left: -50%; -webkit-transform : translate3d(0, -50%, 0); transform : translate3d(0, -50%, 0); background-color: black; color:white; }
flex居中
<p class="parent"> <p class="children">我是通过flex的水平垂直居中噢!</p> </p>
html,body{ width: 100%; height: 200px; } .parent { display:flex; align-items: center;/*垂直居中*/ justify-content: center;/*水平居中*/ width:100%; height:100%; background-color:red; } .children { background-color:blue; }
评论前必须登录!
注册