Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Text-align does not apply to images

Tags:

html

css

I just wrote the following code

<img src="http://www.lorempixel.com/100/100"><img src="http://www.lorempixel.com/100/150" id="test">
#test {
    text-align: center;
}

But the image is not centering. I also used text-align: right which did not work either. I can use float and margin-left but I'm curious why its not working with text-align.

like image 821
Ali Nouman Avatar asked Jan 31 '12 06:01

Ali Nouman


3 Answers

Have a look at text-align css property as described on w3.org website. It says that this property applies to block containers.

Now, the <img> tag itself is not a container (it cannot contain any thing) hence the text-align property does not work as expected. To make an image center-align, there are various ways; the simplest of them is to specify text-align: center on its parent element.

like image 153
Salman A Avatar answered Oct 17 '22 08:10

Salman A


This property specifies how the inline content of a block is aligned, when the sum of the widths of the inline boxes is less than the width of the line box.

Try putting the img in a div with inline-block specified and the first image as the background image of the div.

something like:

<div style="display: block; text-align: center; background-image:url([your_first_image]);">
    <img src="[your_second_image]"/>
</div>

However, this probably will not work on an image, you need to use float, padding or something of that nature.

like image 30
Jonathan Henson Avatar answered Oct 17 '22 08:10

Jonathan Henson


img {
display: block;
margin-left: auto;
margin-right: auto;
}

It should work! It worked for me :D

like image 34
tscpp Avatar answered Oct 17 '22 08:10

tscpp