天天看點

css圖檔的水準居中和垂直居中css圖檔水準居中css圖檔垂直居中

css圖檔水準居中

利用margin:0 auto;實作圖檔水準居中

<div style="width: 500px; border: green solid 1px;">
<img alt="" src="https://www.baidu.com/img/baidu_jgylogo3.gif" style="display:block; margin: 0 auto;" />
</div>
           

利用文本的水準屬性text-align:center;

注意:img本身為行内塊元素(inline-block)

<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>
           

利用絕對定位實作圖檔垂直居中

需要知道圖檔的寬度和高度(或者直接使用padding或margin來實作)

<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布局實作css圖檔垂直居中

css代碼:
<style type="text/css">
/*web前端開發http://www.51xuediannao.com/*/
        .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>
           

轉載于:https://my.oschina.net/u/3160839/blog/2045690