Center image element in parent div

后端 未结 4 951
情深已故
情深已故 2020-11-28 14:58

How I can set center an image element inside a parent div? I would like to do this so that the middle of the image is always in the center of his parent. Also I want the ima

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

    Try giving the image margin property as margin:0 auto, if your parent div has width so the image will be centered as per parent

    0 讨论(0)
  • 2020-11-28 15:14

    I would add this to .box img.

    .box img { margin-left: -25%; margin-top: -25%; }
    

    You would probably need to ajust these per image, or maybe not due to the dimensions.

    0 讨论(0)
  • 2020-11-28 15:23

    Add text-align: center; CSS declaration to the parent .box instead of the children .box img.

    .box {
        height: 100%;
        width: 450px;
        border: 2px solid red;
        background: green;
        overflow: hidden;
        text-align: center;  /* align center all inline elements */
    }
    

    Here is the Fiddle.

    Update

    It seems there's also a 5px gap under the image, It belongs to the line height reserved characters. To remove that from inline elements like <img> you can use vertical-align: bottom:

    .box img {
        height: 100%;
        width: auto;
        vertical-align: bottom; /* <-- fix the vertical gap */
    }
    

    JSFiddle Demo #2

    0 讨论(0)
  • 2020-11-28 15:23

    You'll need to move the text-align: center; from the CSS for the image to the CSS for its parent div, so your CSS looks like this:

    .box {
        height: 100%;
        width: 450px;
        border: 2px solid red;
        background: green;
        overflow: hidden; 
        text-align:center
    }
    
    .box img {
        height: 100%;
        width: auto;
    }
    

    And that's it!

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