Is the property text-align: center;
a good way to center an image using CSS?
img {
text-align: center;
}
I would use a div to center align an image. As in:
<div align="center"><img src="your_image_source"/></div>
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.
text-align
property: and may be you would not like this side effect.References
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
).
Simply change parent align :)
Try this one on parent properties:
text-align:center
If you want to set the image as the background, I've got a solution:
.image {
background-image: url(yourimage.jpg);
background-position: center;
}
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 */
}