我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
这对我来说很管用:
<body>
<table id="table-foo">
<tr><td>
<img src="foo.png" />
</td></tr>
</table>
</body>
<style type="text/css">
html, body {
height: 100%;
}
#table-foo {
width: 100%;
height: 100%;
text-align: center;
vertical-align: middle;
}
#table-foo img {
display: block;
margin: 0 auto;
}
</style>
其他回答
我有一个图片库,我不知道准确的高度或宽度的图像之前,我只知道他们是小于div,他们将被包含。
通过在容器上组合行高设置并在图像元素上使用vertical-align:middle,我最终使用以下HTML标记和以下CSS使其在FF 3.5、Safari 4.0和IE7.0上工作。
HTML标记
<div id="gallery">
<div class="painting">
<a href="Painting/Details/2">
<img src="/Content/Images/Paintings/Thumbnail/painting_00002.jpg" />
</a>
</div>
<div class="painting">
...
</div>
...
</div>
CSS
div.painting
{
float:left;
height:138px; /* fixed dimensions */
width: 138px;
border: solid 1px white;
background-color:#F5F5F5;
line-height:138px;
text-align:center;
}
div.painting a img
{
border:none;
vertical-align:middle;
}
我一直在尝试用hmtl和css让图像在圆形内垂直和水平居中。
在结合了这篇文章中的几个观点后,我得出了以下结论:jsFiddle
下面是三列布局中的另一个示例:jsFiddle
CSS:
#circle {
width: 100px;
height: 100px;
background: #A7A9AB;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
margin: 0 auto;
position: relative;
}
.images {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
HTML:
<div id="circle">
<img class="images" src="https://png.icons8.com/facebook-like-filled/ios7/50" />
</div>
这是正确的:
display: block;
margin-left: auto;
margin-right: auto
否则,如果上面只给你水平居中,试试这个:
.outerContainer {
position: relative;
}
.innerContainer {
width: 50px; //your image/element width here
height: 50px; //your image/element height here
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
我将设置你的大div位置:相对;然后为你的形象这样做:
img.classname{
position:absolute;
top:50%;
left:50%;
margin-top:-25px;
margin-left:-25px;
}
这只是因为你知道图像和包含的div的尺寸。这也可以让你在包含的div中有其他项目…而使用行高之类的解决方案则不会。
编辑:注意…你的页边距是图像大小的负一半。
适用于旧浏览器(IE >= 8)
绝对位置与自动边距相结合可以使元素水平和垂直居中。元素位置可以基于使用相对定位的父元素位置。查看结果
img {
position: absolute;
margin: auto;
top: 0;
left: 0;
right: 0;
bottom: 0;
}