Center image using text-align center?

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

    display: block with margin: 0 didn't work for me, neither wrapping with a text-align: center element.

    This is my solution:

    img.center {
        position: absolute;
        transform: translateX(-50%);
        left: 50%;
    }
    

    translateX is supported by most browsers

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

    Use:

    <dev class="col-sm-8" style="text-align: center;"><img src="{{URL('image/car-trouble-with-clipping-path.jpg')}}" ></dev>
    

    I think this is the way to center an image in the Laravel framework.

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

    You can use text-align: center on the parent and change the img to display: inline-block → it therefore behaves like a text-element and is will be centered if the parent has a width!

    img {
        display: inline-block
    }
    
    0 讨论(0)
  • 2020-11-21 18:37

    That will not work as the text-align property applies to block containers, not inline elements, and img is an inline element. See the W3C specification.

    Use this instead:

    img.center {
        display: block;
        margin: 0 auto;
    }
    <div style="border: 1px solid black;">
    <img class="center" src ="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">
    
    </div>

    0 讨论(0)
  • 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:

    <p>Hello the following image is centered</p>
    <p class="pic"><img src="https://twimg0-a.akamaihd.net/profile_images/440228301/StackoverflowLogo_reasonably_small.png"/></p>
    <p>Did it work?</p>
    

    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.

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

    If you are using a class with an image then the following will do

    class {
        display: block;
        margin: 0 auto;
    }
    

    If it is only an image in a specific class that you want to center align then following will do:

    class img {
        display: block;
        margin: 0 auto;
    }
    
    0 讨论(0)
提交回复
热议问题