我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
这对我很管用。将此添加到image css:
img
{
display: block;
margin: auto;
}
其他回答
这是另一种将所有内容居中的方法。
工作小提琴
HTML:(一如既往的简单)
<div class="Container">
<div class="Content"> /*this can be an img, span, or everything else*/
I'm the Content
</div>
</div>
CSS:
.Container
{
text-align: center;
}
.Container:before
{
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
.Content
{
display: inline-block;
vertical-align: middle;
}
好处
容器和内容高度未知。
居中没有特定的负边距,没有设置行高(所以它适用于多行文本),没有脚本,也适用于CSS过渡。
使用定位。下面的方法对我很有效:
div{
display:block;
overflow:hidden;
width: 200px;
height: 200px;
position: relative;
}
div img{
width: 50px;
height: 50px;
top: 50%;
left: 50%;
bottom: 50%;
right: 50%;
position: absolute;
}
我将设置你的大div位置:相对;然后为你的形象这样做:
img.classname{
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;
}
这只是因为你知道图像和包含的div的尺寸。这也可以让你在包含的div中有其他项目…而使用行高之类的解决方案则不会。
编辑:注意…你的页边距是图像大小的负一半。
在div中
style="text-align:center; line-height:200px"
.container {
height: 200px;
width: 200px;
float:left;
position:relative;
}
.children-with-img {
position: absolute;
width:50px;
height:50px;
left:50%;
top:50%;
transform:translate(-50%);
}