Picture horizontal and vertical centering

The first: as an element of the background image

<style>
    #app{
        width: 500px;
        height: 500px;
        background: #ccc url('../../../static/images/demo.png') no-repeat center center;
    }    
</style>
<div id="app"></div>

The second: img tag mode

  • 1: flex layout
<style>
    #app{
        width:500px;
        height: 500px;
        display:flex;
        justify-content:center;
        align-items:center;
    }
</style>
<div id="app">
    <img src="../../../static/images/demo.png">
</div>
  • 2:display:table-cell + vertical-align :middle
<style>
    #app{
        width:500px;
        height: 500px;
        text-align:center;
        display:table-cell;
        vertical-align:middle
    }
</style>
<div id="app">
    <img src="../../../static/images/demo.png">
</div>
  • 3: position absolute positioning
<style>
    #app{
        width:500px;
        height: 500px;
        position:relative
    }
    img{
        position:relative;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%)
    }
</style>
<div id="app">
    <img src="../../../static/images/demo.png">
</div>
  • 4: vertical-align vertically disposed centrally
<style>
    #app{
        width:500px;
        height: 500px;
        text-align:center
    }
    span{
        display:inline-block;
        height:100%;
        vertical-align:middle
    }
    img{
        vertical-align:middle
    }
</style>
<div id="app">
    <span></span>
    <img src="../../../static/images/demo.png">
</div>

Guess you like

Origin www.cnblogs.com/homehtml/p/11838715.html