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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11206109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 01:17:01  来源:igfitidea点击:

how to put image in center of html page?

htmlcssvertical-alignment

提问by Darko Rodic

Possible Duplicate:
How to center div horizontally and vertically

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

I need to put image in center of html page, both vertical and horizontal ... been trying few stuff but seems to work fine. To get horizontal alignment I used <body style="text-align:center">

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

and it works fine, but what do with vertical alignment?

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

regards

问候

回答by Mateusz Kocz

If:

如果:

X is image width,
Y is image height,

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

then:

然后:

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

But keep in mind this solution is valid only if the only element on your site will be this image. I suppose that's the case here.

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

Using this method gives you the benefit of fluidity. It won't matter how big (or small) someone's screen is. The image will always stay in the middle.

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

回答by Danny

Put your image in a container div then use the following CSS (changing the dimensions to suit your image.

将您的图像放在容器 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*/
    }

回答by Rohit Azad

Hey now you can give to body background image

嘿现在你可以给身体背景图片

and set the background-position:center center;

并设置 background-position:center center;

as like this

像这样

body{
background:url('../img/some.jpg') no-repeat center center;
min-height:100%;
}

回答by Eamonn

There are a number of different options, based on what exactly the effect you're going for is. Chris Coyier did a piece on just this way back when. Worth a read:

有许多不同的选项,具体取决于您要达到的效果。Chris Coyier 曾在这方面做过一篇文章。值得一读:

http://css-tricks.com/perfect-full-page-background-image/

http://css-tricks.com/perfect-full-page-background-image/