It totally depends on your requirement, there are various ways to do so, one is that img
is an inline
element, so setting it to block
and using margin: auto;
will center
your img
img {
display: block;
margin: auto;
}
Another way is which you are trying to attempt, which needs text-align: center;
to be declared on the parent element and not the img
tag itself, cuz I doubt you are using text-align: center;
for the img
tag and not for the parent... Where in the above solution we are targeting the img
tag, so there's a difference between the two..
What's the good point here?
- You don't have to make the
img
ablock
level element. - No need of
margin: auto;
What's the bad point here?
- If you have
p
elements inside thediv
, they will be centered aligned as well, because thealign
property is inherited.
So what to do now? Align the p
elements to the left
using text-align: left;
property, and here we will be targetting p
like
This will keep the image centered and will align the p
to the left
.wrap {
text-align: center;
}
.wrap p {
text-align: left;
}
Last but not the least, we can also use CSS Positioning where you can have a parent element set to position: relative;
and than we use position: absolute;
for the img
tag, and than we assign top: 50%
and left: 50%
and than we deduct the 1/2 of total height
and width
of your img
by using margin-top
and margin-left
properties respectively. This method comes handy in case where you need the image vertically as well as horizontally centered. (This method will require fixed height
and width
to be declared)