Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center image using text-align center?

Tags:

html

css

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

img {     text-align: center; } 
like image 936
Web_Designer Avatar asked Aug 14 '11 06:08

Web_Designer


People also ask

How do I center a image in HTML?

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.

How do I center align an image in CSS?

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.


1 Answers

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>
like image 88
Mrchief Avatar answered Oct 23 '22 17:10

Mrchief