vertical alignment of image inside a div

前端 未结 6 871
星月不相逢
星月不相逢 2020-12-16 00:36

I want to set vertical alignment of image inside a div. I use img { vertical-align:middle} but it is not working.

6条回答
  •  我在风中等你
    2020-12-16 01:10

    This is a solution that doesn't require JavaScript (as my previous solution did).

    You can achieve what you want by assigning display: table-cell to the containing div. Here's an example: http://jsbin.com/evuqo5/2/edit

    I feel I must warn you that you will need to test this in every browser you intend to support. Support for the table-cell value is fairly new, particularly in Firefox. I know it works in Firefox 4, but I don't know about any of the 3.x iterations. You'll also want to test in IE (I've only tested in Chrome 10 and Firefox 4).

    The CSS:

      div#container {
        width: 700px;
        height: 400px;
        position: relative;
        border: 1px solid #000;
        display: table-cell;
        vertical-align: middle;  
      }
      div#container img {
        margin: 0 auto;
        display: block;
      }
    

    You won't need the div#container img styles if you don't also want to horizontally align the image.

提交回复
热议问题