Centering an image within a div

前端 未结 6 2007
予麋鹿
予麋鹿 2020-12-01 11:25

I have already set the border of an image within a div to be none. I now want to center that image within its containing div. I have tried using the mar

相关标签:
6条回答
  • 2020-12-01 11:47

    Try setting the image’s display property to block:

    banner {
        height: 100px;
        width: 960px;
        padding-bottom: 10px;
    }
    
    banner img {
        border: none;
        display: block;
        margin: 0 auto;
    }
    
    0 讨论(0)
  • 2020-12-01 11:57

    horizontal: just try

    text-align:center;
    

    :)

    0 讨论(0)
  • 2020-12-01 11:58

    I believe it is just margin: auto;. No zero needed.

    0 讨论(0)
  • 2020-12-01 12:03

    Either

    banner {
         height:100px;
         text-align:center;
         width:960px;
         padding-bottom:10px;}
    

    or if the img is of specific size then

    banner img {
             display:block;
             width: <somevalue>px;
             border:none;
             margin:0 auto;
             }
    

    will work ..

    0 讨论(0)
  • 2020-12-01 12:06

    After many exhaustive tries to center align an image in a div (vertically and/or horizontally), I understood the following.
    To vertically center align an image in a div.

    .div {
     display:flex;
    justify-content:center
    }
    

    To horizontally center align an image in a div.

    .div {
    display:flex;
    align-items:center;
    }
    

    To center both vertically and horizontally an image in a div, there are 2 options (1)

    div {
    display:flex;
    align-items:center;
    justify-content:center;
    }
    

    (2)

    .div {
    display:flex
    }
    
    .div > img {
    margin: auto
    }
    
    0 讨论(0)
  • 2020-12-01 12:10

    Applying text-align: center to your banner div will center its inline and inline-block children (which encompasses the img tag).

    The reason why your code wasn't working is because margin: 0 auto will only center block elements.

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