在网页中让一个未知高度的块元素水平垂直居中是一个老生常谈的问题,但是总是有些特殊场景让你无法得心应手的实现居中,本文介绍几种常用的经典的居中方法,总有一种适合你!
1. position
.parent { ???width: 200px; ???height: 200px; ???margin: auto; ???border: 1px solid red; ???position: relative;}.child { ???position: absolute; ???width: 100px; ???height: 50%; ???top: 0; ???left: 0; ???right: 0; ???bottom: 0; ???margin: auto; ???background-color: red;}
2. flex
.parent { ???width: 200px; ???height: 200px; ???margin: auto; ???border: 1px solid red; ???display: -webkit-box; ???display: -moz-box; ???display: -ms-flexbox; ???display: -webkit-flex; ???display: flex; ???-webkit-box-pack: center; ???-webkit-justify-content: center; ???-ms-flex-pack: center; ???justify-content: center; ???-webkit-box-align: center; ???-webkit-align-items: center; ???-ms-flex-align: center; ???align-items: center;}.child { ???width: 100px; ???height: 50%; ???background-color: red;}
3. translate
.parent { ???width: 200px; ???height: 200px; ???margin: auto; ???border: 1px solid red; ???position: relative;}.child { ???width: 100px; ???height: 50%; ???background-color: red; ???position: absolute; ???left: 50%; ???top: 50%; ???transform: translate(-50%, -50%);}
4. calc
.parent { ???width: 200px; ???height: 200px; ???margin: auto; ???border: 1px solid red; ???position: relative;}.child { ???width: 100px; ???height: 50%; ???background-color: red; ???position: absolute; ???left: -webkit-calc(50% - 25%); ???left: -moz-calc(50% - 25%); ???left: -ms-calc(50% - 25%); ???left: calc(50% - 25%); ???top: -webkit-calc(50% - 25%); ???top: -moz-calc(50% - 25%); ???top: -mz-calc(50% - 25%); ???top: calc(50% - 25%);}
本文介绍的四种方法全部由以下实例验证通过,且加了兼容性前缀,可以直接复制使用,建议使用时可以按顺序考虑,具体可看个人习惯,反正我是这个顺序,因为可以少写很多兼容性前缀,大家可以放心大胆的粘贴使用了,拿贴不谢!
布局如下:
效果如下:
巧用CSS居中未知高度的块元素
原文地址:http://www.cnblogs.com/lewiscutey/p/7501974.html