Vertical Align Middle an image in an a tag in a div

梦想的初衷 提交于 2019-12-11 01:57:27

问题


This has probably been done before but I can't find a solution for my specific case. I have the following:

<div class="holder" style="height:260px;width:260px;">
<a href="#"><img src="image.jpg" /></a>
</div>

How can I get the image to align into the middle of the div?


回答1:


Normally, img is an inline-element, which means, that it's being aligned to the baseline of the text of your parent-element. This leaves a nasty space underneath your image.

You can prevent this with

img{
   display:[inline-]block; /* or inline-block if the img isn't the only element in your div*/
}

This removes the reserved space underneath the image.

you can change the alignment by

img{
   vertical-align: [top|middle|bottom|baseline|...] ;
}

to align it according to your text.

In general, you can only vertical-align inline elements. So an image with display:block won't be affected by a vertical alignment declaration.




回答2:


Add

text-align: center;
vertical-align: middle; 
display: table-cell;

to the div's style.




回答3:


Try :

.img
{
display: block;
margin-left: auto;
margin-right: auto 
}



回答4:


If this is your mark up then you can use line-height property for this. Like this:

.holder{
    line-height:260px;
}


来源:https://stackoverflow.com/questions/9583289/vertical-align-middle-an-image-in-an-a-tag-in-a-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!