Image center align vertically and horizontally

This question already has an answer here:

  • How to center an element horizontally and vertically? 13 answers

  • There's a few good ways to both horizontally and vertically center an element, it just comes down to the situation and your preference.

    With the following markup:

    <div><img src="a.png" width="100" height="100"></div>
    

    line-height

    div { width:300px; height:300px; line-height:300px; text-align:center; }
    div img { vertical-align:middle; }
    

    Good quick fix without messing with position ing too much but if actually text is being centered this way could be problematic.

    display:table-cell

    div { width:300px; height:300px; text-align:center; display:table-cell; vertical-align:middle; }
    

    Works just like good old tables and highly flexible, however only supported in modern browsers.

    position:absolute

    div { width:300px; height:300px; position:relative; }
    div img { top:-50px; left:-50px; position:absolute; margin:50% 0 0 50%; }
    

    top and left offsets should be set to half the respective dimensions of the element being positioned. Works well if the containing element needs to be flexible but absolute values are required to work.


    Demo of all techniques: jsfiddle.net/Marcel/JQbea (fullscreen)


    why not just remove the img tags then set the image as a background and center it like this:

    (doing it inline, but via external css file is the best way)

    <div style="background: url('7-612x612-2.png') no-repeat center center transparent;">&nbsp;</div>
    
    链接地址: http://www.djcxy.com/p/41490.html

    上一篇: 与div对齐高度100%

    下一篇: 图像中心垂直和水平对齐