對於非 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 居中方式,但願各位大神們補充起來。