我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
我有一个div 200x200px。我想在div的中间放置一个50 x 50 px的图像。
怎样才能做到呢?
我能够得到它的中心水平使用文本对齐:中心的div。但垂直对齐是问题..
当前回答
你可以用下面的代码水平和垂直地居中一个图像(在IE/FF中工作)。 它会将图像的上边缘放置在浏览器高度的50%,而margin-top(向上拉图像高度的一半)将完美地居中。
<style type="text/css">
#middle {position: absolute; top: 50%;} /* for explorer only*/
#middle[id] {vertical-align: middle; width: 100%;}
#inner {position: relative; top: -50%} /* for explorer only */
</style>
<body style="background-color:#eeeeee">
<div id="middle">
<div id="inner" align="center" style="margin-top:...px"> /* the number will be half the height of your image, so for example if the height is 500px then you will put 250px for the margin-top */
<img src="..." height="..." width="..." />
</div>
</div>
</body>
其他回答
当然,另一种方法是使用valign创建一个表。不管你是否知道div的高度,这都可以工作。
<div>
<table width="100%" height="100%" align="center" valign="center">
<tr><td>
<img src="foo.jpg" alt="foo" />
</td></tr>
</table>
</div>
但只要可能,您应该始终坚持只使用CSS。
垂直对齐是最常被误用的css样式之一。对于不是td或css“display: table-cell”的元素,它不能像你期望的那样工作。
这是一篇关于这个问题的很好的文章。http://phrogz.net/CSS/vertical-align/index.html
实现你想要的目标最常见的方法是:
填充上/下 绝对位置 行高
这是正确的:
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;
}
这对我来说很管用:
<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>
我一直在尝试用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>