Center image using text-align center?

后端 未结 24 1610
终归单人心
终归单人心 2020-11-21 17:53

Is the property text-align: center; a good way to center an image using CSS?

img {
    text-align: center;
}
24条回答
  •  死守一世寂寞
    2020-11-21 18:37

    Only if you need to support ancient versions of Internet Explorer.

    The modern approach is to do margin: 0 auto in your CSS.

    Example here: http://jsfiddle.net/bKRMY/

    HTML:

    Hello the following image is centered

    Did it work?

    CSS:

    p.pic {
        width: 48px;
        margin: 0 auto;
    }
    

    The only issue here is that the width of the paragraph must be the same as the width of the image. If you don't put a width on the paragraph, it will not work, because it will assume 100% and your image will be aligned left, unless of course you use text-align:center.

    Try out the fiddle and experiment with it if you like.

提交回复
热议问题