html - 水平div中的中心图像
这个问题在这里已有答案:
使用文本对齐中心的中心图像? 23个答案
我有一个img在一个div(class="top_image"),我希望这个图像正好在div的中间,但我没有尝试工作......
谢谢你的帮助!
7个解决方案
473 votes
此处发布的每个解决方案都假定您知道min-width的尺寸,这不是常见情况。 而且,将尺寸种植到溶液中是痛苦的。
只需设置:
/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;
要么
/* for the img inside your div */
display: block;
margin: 0 auto;
就这样。
请注意,您还必须为外部div设置初始值min-width。
Dyin answered 2019-03-24T08:28:57Z
25 votes
text-align:center仅适用于水平居中。 要使它处于完整的中心,垂直和水平,您可以执行以下操作:
div
{
position: relative;
}
div img
{
position: absolute;
top: 50%;
left: 50%;
margin-left: [-50% of your image's width];
margin-top: [-50% of your image's height];
}
Maxime Fabre answered 2019-03-24T08:29:24Z
9 votes
W3C提供了一个非常简单和优雅的解决方案。 只需使用保证金:0自动声明如下:
.top_image img { margin:0 auto; }
来自W3C的更多信息和示例。
Phil Thomas answered 2019-03-24T08:29:59Z
6 votes
CSS
img
{
max-width: 100%;
max-height: 100%;
display: block;
margin: auto auto;
}
.outer
{
border: 1px solid #888;
width: 100px;
height: 100px;
}
.inner
{
display:table-cell;
height: 100px;
width: 100px;
vertical-align: middle;
}
Ads answered 2019-03-24T08:30:20Z
5 votes
我认为最好为div做文本对齐中心,让图像处理高度。 只需指定div的顶部和底部填充,即可在图像和div之间留出空间。 看看这个例子:[http://jsfiddle.net/Tv9mG/]
Jay answered 2019-03-24T08:30:46Z
3 votes
我希望这会有所帮助:
.top_image img{
display: block;
margin: 0 auto;
}
Arasu Pandiyan answered 2019-03-24T08:31:19Z
-3 votes
这花了我太长时间才弄明白。 我不敢相信没人提到中心标签。
例如:

如果要将图像调整为百分比:

GG美国
DisgruntledHuman answered 2019-03-24T08:32:04Z