Because everybody has added the answers using something similar. I decided to share this with everyone. You can use this solution for image in center for both x (horizontal)
and y (vertical)
axis because that is what question title says. This relays on flexbox
.
<div id="imageBox">
<img src="my-image.png" alt="some text" />
</div>
#imageBox
{
display:flex;
flex-direction:column;
justify-content:center;
width: 400px;
height: 400px;
}
#imageBox img
{
margin: 0 auto; /* this is where magic will happen!! */
}
Here is the DEMO of above approach.
If you want to center only horizontally using flexbox
just omit styles for img
and set the following.
#imageBox
{
display: flex;
flex-direction: row; /* changed from column to row */
justify-content: center;
}
Notice i have changed flex-direction
property from column
to row
which is default. If you do not specify it will still work. Setting it to column
will make it center vertically.
There are some things that should be kept in mind with while working with flexbox.
- flexbox is not supported in older IE versions i.e. IE < 11 and has limited support for IE-10.
- The parent container (
#imgBox
in this case) should have some height and width otherwise the image will not center in one of the axis. This is also required for margin: 0 auto to work i.e. without some having width
(not in percentage), the margin: 0 auto
property will not work in CSS
.
Alternative approach:
If you do want to rely on flexbox then it is again not much difficult. Images are inline
in nature on web pages but they still can have width
and height
so they can be centered horizontally using text-align
property i.e. using the above example...
#imageBox
{
text-align: center;
}
However it will not center the img
vertically. Vertical-align
alone will not center the image vertically in this case. For that you can check this post here. It is nicely explained there.
You can also use display: table
and display: table-cell
and apply text-align: center
and vertical-align: middle
on table-cell
to center the content on both axis but i would not recommend these unless really necessary.