如何将图像放在html页面的中心?

Dar*_*dic 14 html css vertical-alignment

可能重复:
如何水平和垂直居中div

我需要把图像放在html页面的中心,纵向和横向......一直在尝试一些东西,但似乎工作正常.为了得到我使用的水平对齐 <body style="text-align:center">

它工作正常,但垂直对齐怎么办?

问候

Mat*_*ocz 22

如果:

X是图像宽度,
Y是图像高度,

然后:

img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -(X/2)px;
    margin-top: -(Y/2)px;
}
Run Code Online (Sandbox Code Playgroud)

但请记住,只有当您网站上的唯一元素是此图片时,此解决方案才有效.我想这就是这种情况.

使用此方法可为您带来流动性.某人的屏幕有多大(或小)并不重要.图像将始终保持在中间.

  • 如果您不知道图像的大小,那么只需将`margin-left`和`margin-top`行替换为:`transform:translate(-50%, - 50%);` (5认同)

Dan*_*nny 9

将图像放入容器div中,然后使用以下CSS(更改尺寸以适合您的图像).

.imageContainer{
        position: absolute;
        width: 100px; /*the image width*/
        height: 100px; /*the image height*/
        left: 50%;
        top: 50%;
        margin-left: -50px; /*half the image width*/
        margin-top: -50px; /*half the image height*/
    }
Run Code Online (Sandbox Code Playgroud)