我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
我们可以使用flex轻松实现这一点。不需要背景图片。
<!DOCTYPE html > < html > < >头 <时尚> # image-wrapper { 宽度:500 px; 身高:500 px; 边框:1px实体#333; 显示:flex; justify-content:中心; 对齐项目:中心; } > < /风格 > < /头 身体< > < div id = " image-wrapper " > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div > < /身体> < / html >
其他回答
easy
img {
transform: translate(50%,50%);
}
谢谢大家提供的线索。
我用了这个方法
div.image-thumbnail
{
width: 85px;
height: 85px;
line-height: 85px;
display: inline-block;
text-align: center;
}
div.image-thumbnail img
{
vertical-align: middle;
}
这是一种老式的解决方案,但浏览器市场份额已经足够大了,如果你不担心IE7的性能下降,你可能不需要IE黑客的部分。当你知道外部容器的尺寸,但可能知道也可能不知道内部图像的尺寸时,这种方法是有效的。
.parent {
display: table;
height: 200px; /* can be percentages, too, like 100% */
width: 200px; /* can be percentages, too, like 100% */
}
.child {
display: table-cell;
vertical-align: middle;
margin: 0 auto;
}
<div class="parent">
<div class="child">
<img src="foo.png" alt="bar" />
</div>
</div>
你可以使用以下属性轻松做到这一点:
#内容{ 显示:flex; 对齐项目:中心; 宽度:200 px; 身高:200 px; 边框:1px纯红色; } # myImage { 显示:块; 宽度:50 px; 高度:50 px; 保证金:汽车; 边框:1px纯黄色; } < div id = "内容" > <img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png"> < / div >
引用:W3
这对我很管用。将此添加到image css:
img
{
display: block;
margin: auto;
}