Is the property text-align: center;
a good way to center an image using CSS?
img {
text-align: center;
}
There are three methods for centering an element that I can suggest:
Using the text-align
property
.parent {
text-align: center;
}
Using the margin
property
img {
display: block;
margin: 0 auto;
}
Using the position
property
img {
display: block;
position: relative;
left: -50%;
}
.parent {
position: absolute;
left: 50%;
}
The first and second methods only work if the parent is at least as wide as the image. When the image is wider than its parent, the image will not stay centered!!!
But: The third method is a good way for that!
Here's an example:
img {
display: block;
position: relative;
left: -50%;
}
.parent {
position: absolute;
left: 50%;
}