Center image using text-align center?

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

    I would use a div to center align an image. As in:

    <div align="center"><img src="your_image_source"/></div>
    
    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-21 18:39

    Actually, the only problem with your code is that the text-align attribute applies to text (yes, images count as text) inside of the tag. You would want to put a span tag around the image and set its style to text-align: center, as so:

    span.centerImage {
         text-align: center;
    }
    <span class="centerImage"><img src="http://placehold.it/60/60" /></span>

    The image will be centered. In response to your question, it is the easiest and most foolproof way to center images, as long as you remember to apply the rule to the image's containing span (or div).

    0 讨论(0)
  • 2020-11-21 18:39

    Simply change parent align :)

    Try this one on parent properties:

    text-align:center
    
    0 讨论(0)
  • 2020-11-21 18:39

    If you want to set the image as the background, I've got a solution:

    .image {
        background-image: url(yourimage.jpg);
        background-position: center;
    }
    
    0 讨论(0)
  • 2020-11-21 18:39

    One more way to scale - display it:

    img {
      width: 60%; /* Or required size of image. */
      margin-left: 20% /* Or scale it to move image. */
      margin-right: 20% /* It doesn't matters much if using left and width */
    }
    
    0 讨论(0)
提交回复
热议问题