繁体   English   中英

如何将未知大小的图像居中放置在 div 中?

[英]How to center the image of unknown size inside div?

假设我有一个具有以下样式的div

#container {
    position: fixed;
    width: 100%;
    height: 100%;
}

另外我有一张未知尺寸的图像(尺寸可能会有所不同),我想垂直和水平对齐。

这样做的最佳方法是什么?

背景图像方法将起作用,背景位置:中心居中,不幸的是您将失去对图像缩放的控制。

您可以按如下方式设置您的图像:

position:absolute;
margin:auto;
top:0;
bottom:0;
left:0;
right:0;

附注。 请记住,这将相对于其最近定位的父项居中。

添加以下内容:

前两行垂直居中,最后一行水平居中。

display: table-cell;
vertical-align: middle ;
text-align: center;

更多信息可以在这里找到: http : //www.w3.org/Style/Examples/007/center

最简单的跨浏览器方法是将动态图像设置为#container上的背景属性:

<div id="container" style="background: url(path/to/image.png) no-repeat 50% 50%"></div>

这将垂直和水平居中。

#container {
    text-align: center;
    vertical-align: middle;
    display: table-cell;
}

http://jsfiddle.net/nfBDT/

我相信最简单的方法是这样做:

.container img {
    display:block;
    margin:auto;
}

调整 .container 以适合您的 div(不确定您的 div 是类还是 ID)

哦,我没有阅读您的所有问题。

这似乎有效:

<style type="text/css">
.wraptocenter {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: ...;
    height: ...;
}
.wraptocenter * {
    vertical-align: middle;
}
/*\*//*/
.wraptocenter {
    display: block;
}
.wraptocenter span {
    display: inline-block;
    height: 100%;
    width: 1px;
}
/**/
</style>
<!--[if lt IE 8]><style>
.wraptocenter span {
    display: inline-block;
    height: 100%;
}
</style><![endif]-->

全额信用: http : //www.brunildo.org/test/img_center.html

http://zoffix.com/new/absolute-center-random-width-height.html

这是一个相当不错的例子。 通常你在现代浏览器中使用 table/vertical-align,在 IE 中使用定位+%s。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM