对于非 inline 元素内的文字水平居中均可以经过 text-align: center;
完成。css
也能够设置 margin: 0 auto;
html
这种场景一般在修正 input 框光标和文字的位置。设置 line-height
的值等于 height
便可。flex
/Users/alex/Desktop/24319F76-DE76-4A5A-840D-8EC7C0C43882.png
例如图中的情况,须要文字相对于图片的垂直居中,经过对图片设置vertical-align: middle;
便可。vertical-align
其实能够完成多种相对对其,例如 top,baseline
等等。优化
本方法应该是用的很是多的了,直接看代码吧code
.outer { width: 100%; height: 500px; position: relative; } .inner { position: absolute; width: 200px; height: 200px; top: 50%; left: 50%; margin: -100px 0 0 -100px; background-color: blue; }
上面方法在 css 中加入 calc 以后能够作以下优化 (安卓 4.3 以上,IE9+)orm
.outer { width: 100%; height: 500px; position: relative; } .inner { position: absolute; width: 200px; height: 200px; top: calc(50% - 100px); left: calc(50% - 100px); background-color: blue; }
html:htm
<div class="outer"> <div class="inner"> <p>asjdhajshdkjhakjdshk</p> <p>sdalskjdkajls</p> </div> </div>
table 搭配 table-cell 的方法图片
.outer { width: 100%; height: 300px; display: table; text-align: center; } .inner { display: table-cell; vertical-align: middle; }
translate 方法(IE9 以上)input
.outer { width: 100%; height: 500px; position: relative; } .inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
flex 方法
该方法就很是简单了,只须要设置 outerit
.outer { width: 100%; height: 500px; display: flex; justify-content: center; align-items: center; }
html 模版沿用上面
.outer { width: 100%; height: 500px; position: relative; text-align: center; } .inner { height: 100px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; }
我相信本文绝对不是最全的 css 居中方式,但愿各位大神们补充起来。