利用margin: 0 auto實現圖片居中就是在圖片上加上css樣式margin: 0 auto 以下:javascript
<div style="text-align: center; width: 500px; border: green solid 1px;"> <img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="margin: 0 auto;" /> </div>
代碼以下:php
<div style="text-align: center; width: 500px; border: green solid 1px;"> <img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="display: inline-block;" /> </div>
這種方法是要註明高度才能夠使用,代碼以下:css
<div style="text-align: center; width: 500px;height:200px; line-height:200px; border: green solid 1px;"> <img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="display: inline-block; vertical-align: middle;" /> </div>
利用table的方法是利用了table的垂直居中屬性,代碼以下:html
這裏使用display: table;和display: table-cell;來模擬table,這種方法並不兼容IE6/IE7,IE67不支持display: table,若是你不須要支持IE67那就能夠用java
缺點:當你設置了display: table;可能會改變你的原有佈局css3
<div style="text-align: center; width: 500px;height:200px; display: table;border: green solid 1px;"> <span style="display: table-cell; vertical-align: middle; ">
<img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="display: inline-block;" />
</span> </div>
若是已知圖片的寬度和高度能夠這樣,代碼以下:web
<div style="width: 500px;height:200px; position: relative; border: green solid 1px;"> <img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="width: 120px; height: 40px;position: absolute; left:50%; top: 50%; margin-left: -60px;margin-top: -20px;" /> </div>
移動端通常瀏覽器版本都比較高,因此能夠大膽的使用flex佈局,(flex佈局參考css3的flex佈局用法)演示代碼以下:瀏覽器
css代碼:
<style type="text/css"> .ui-flex { display: -webkit-box !important; display: -webkit-flex !important; display: -ms-flexbox !important; display: flex !important; -webkit-flex-wrap: wrap; -ms-flex-wrap: wrap; flex-wrap: wrap } .ui-flex, .ui-flex *, .ui-flex :after, .ui-flex :before { box-sizing: border-box } .ui-flex.justify-center { -webkit-box-pack: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center } .ui-flex.center { -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 } </style>
html代碼:
<div class="ui-flex justify-center center" style="border: green solid 1px; width: 500px; height: 200px;"> <div class="cell"> <img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="" /> </div> </div>