Center an image horizontally using CSS

前端 未结 4 1299
野的像风
野的像风 2020-11-28 12:01

I am trying to center a image horizontally using css.

I am displaying my image on the screen with the following HTML code:

相关标签:
4条回答
  • 2020-11-28 12:03

    Try this for your CSS:

    .center img {        
      display:block;
      margin-left:auto;
      margin-right:auto;
    }
    

    and then add to your image to center it:

    class="center"
    
    0 讨论(0)
  • 2020-11-28 12:11

    Use margin

    margin-left:auto;
    margin-right:auto;
    
    0 讨论(0)
  • 2020-11-28 12:22

    use position absolute and margin like this

    img.loading{
      position: absolute;
      left: 50%;
      margin-left: -(half ot the image width)px
    }
    
    0 讨论(0)
  • 2020-11-28 12:25

    You can use different method:

    Method 1:

    Its a simple method, use "text-align: center;" for your parent div.

    #loading {
      text-align: center;
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    Method 2:

    Please check the code:

    #loading img {
      margin: 0 auto;
      display: block;
      float: none; 
      /*width: 200px; if its a large image, it need a width for align center*/
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    Method 3:

    Using "display: flex;"

    #loading {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    Method 4:

    You can use "position: absolute;",

    #loading {
            position: relative;
            }
    #loading img{
            position: absolute;
            top: 0;
            left: 50%;
            margin-right: -50%;
            transform: translate(-50%, 0%);
            -ms-transform: translate(-50%, 0%);
            -webkit-transform: translate(-50%, 0%);
            -moz-transform: translate(-50%, 0%);
            -o-transform: translate(-50%, 0%);
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    Hope this will help you.

    0 讨论(0)
提交回复
热议问题