Is the property text-align: center;
a good way to center an image using CSS?
img { text-align: center; }
Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.
To center an image, we have to set the value of margin-left and margin-right to auto and make it a block element by using the display: block; property. If the image is in the div element, then we can use the text-align: center; property for aligning the image to center in the div.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With