Center image using text-align center?

后端 未结 24 1651
终归单人心
终归单人心 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:38

    To center a non background image depends on whether you want to display the image as an inline (default behavior) or a block element.

    Case of inline

    If you want to keep the default behavior of the image's display CSS property, you will need to wrap your image inside another block element to which you must set text-align: center;

    Case of block

    If you want to consider the image as a block element of its own, then text-align property does not make a sens, and you should do this instead:

    IMG.display {
        display: block;
        margin-left: auto;
        margin-right: auto;
    }
    

    The answer to your question:

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

    Yes and no.

    • Yes, if the image is the only element inside its wrapper.
    • No, in case you have other elements inside the image's wrapper because all the children elements which are siblings of the image will inherit the text-align property: and may be you would not like this side effect.

    References

    1. List of inline elements
    2. Centering things

提交回复
热议问题