建立元素html
<div class="parent"> <div class="child">child</div> </div>
.parent { width:400px; height:400px; background: red; position: relative; } .child { position: absolute; left:50%; top:50%; background: yellow; width:50px; height:50px; margin-left:-25px; margin-top:-25px; }
.parent { width:400px; height:400px; background: red; position: relative; } .child { position: absolute; left:50%; top:50%; transform: translate(-50%,-50%); }
.parent { position:relative; width:200px; height:200px; background: red; } .child { width:80px; height:40px; background: yellow; position: absolute; left:0; top:0; right:0 ; bottom:0; margin:auto; }
.parent { height: 300px; width:400px; border: 1px solid red; display: table-cell; vertical-align: middle; text-align: center; } .child { display: inline-block; width:50px; height:50px; background: blue; } /* 或者 */ .parent { width: 400px; height: 300px; display: table-cell; vertical-align: middle; border: 1px solid red; text-align: center; } .child { display: inline-block; vertical-align: middle; background: blue; }
.parent { width:400px; height:200px; background:red; display: flex; justify-content:center; align-items:center; } .child { height:100px; width:100px; background:green; }
.parent { width:200px; height:200px; background:red; text-align: center; } .child { height:100px; width:100px; background:yellow; display: inline-block; vertical-align: middle; } .parent:before { content:""; height:100%; vertical-align: middle; display: inline-block; }
在下的文章都是學習過程當中的總結,若是發現錯誤,歡迎留言指出~