Center Align an image or div inside another div

Published

To center position an image or div inside another div or exactly in the main page container, we can use CSS.

You might be aware of text-align:center; Css code will do the trick if you only need to position an image or another div inside a big div horizontally (right to left).
But for vertical alignment, it would be a problem.

Solution 1:


If you are trying to display an image inside another div exactly in center, you could set it as the background image and align it to center of the div.

For Example.
Assume that You have a div with id #BigDiv.
and you want to set an image named "myimage.jpg" exactly inside that div with "200" pixels in width, and "200" pixels in height.

Here is the CSS code that might do the trick.

#BigDiv {
background:url(myimage.jpg) no-repeat center center; height:200px; width:200px;
}


One knowing disadvantage of this problem is its not as SEO/reader friendly ,if you could use image src, you can also call alt attribute to make it SEO/reader friendly.

Solution 2:


First we will set our larger div's position as relative.

#BigDiv{position:relative;}

Then we assign a class name for our image. ie.

<img src= "myimage.jpg" class='myimage'/>

Then rest Css Code

.myimage{
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;
}


This works only if we know the dimensions of both the image and the containing div.
Here,our margins are negative half of the size of the image.


Solution 3:

Assume that you know the size of container div and you dont know the dimensions of images.
If you are working with a light-box,or image carousels,it will be useful.
Our container div has the id as #BigDiv

#BigDiv
{
display:table-cell;
vertical-align:middle;
height:200px;
width:200px;
}
img
{
 /*Apply any styling here*/
}



Solution 4:


Another nice solution that might work is to create a table with valign.
This would work even if you know div's height or not.

<div>
<table width="100%" height="100%" align="center" valign="center">
<tr>
<td>
<img src="myimage.jpg" alt="myimage" />
</td>
</tr>
</table>
</div>

But it will be good if you use css solution wherever possible.



Comments

Post a Comment