如何将<img>
置于包含<div>
的中心?
通常margin-left: auto; margin-right: auto;
无效。
图片可以比容器大,并且可以max-width
和max-height
水平或垂直缩放。
使用以下代码的jsfiddle:http://jsfiddle.net/9ShGj/1/
HTML:
<div class="container">
<img src="http://www.yensa.com/fat/fat-dude10.jpg" />
</div>
<div class="container">
<img src="http://oi43.tinypic.com/bje2wn.jpg" />
</div>
CSS:
.container {
width: 200px;
height: 200px;
background: rgb(120, 120, 120);
border: 1px solid red;
margin: 5px;
}
.container img {
max-width: 200px;
max-height: 200px;
margin-left: auto;
margin-right: auto;
vertical-align: middle;
}
答案 0 :(得分:5)
您可以这样写:
<强> CSS 强>
div{
width:200px;
height:200px;
border:1px solid red;
text-align:center;
line-height:200px;
}
img{
vertical-align:middle;
}
<强> HTML 强>
<div>
<img src="http://dummyimage.com/150x150/000/fff&text=dummy" >
</div>
答案 1 :(得分:1)
图像不是块级元素,因此需要将其转换为块级元素
所以在你的CSS添加
.container img {
display:block /*ADD this line*/
max-width: 200px;
max-height: 200px;
margin-left: auto;
margin-right: auto;
vertical-align: middle;
}
此外,您还需要考虑以下几点
Doctype : check whether it is not in quirks mode.
Width of inner div or image must me less that width of parent div.
检查这些事情你会得到你的答案......一切顺利。
答案 2 :(得分:0)
除非你将img作为块级元素,否则你应该能够将它作为中心:
.container { text-align: center; }
答案 3 :(得分:0)
更新CSS ... vertical-align:middle; text-align:center
.container {
width: 200px;
height: 200px;
background: rgb(120, 120, 120);
border: 1px solid red;
margin: 5px;
vertical-align:middle; text-align:center //add this
}