CSS 在网页上垂直和水平居中对齐图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14701527/
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 21:32:54  来源:igfitidea点击:

Center align image vertically & horizontally on a web page

cssalignment

提问by Learning

I need to display simple under contruction page which has an image let us say 800x700px & i want this image to appear at the center of page both vertically & horizontally,

我需要显示简单的构造页面,其中有一个图像让我们说 800x700px & 我希望这个图像垂直和水平地出现在页面的中心,

I tried different approach's but didn't work. Sample html below

我尝试了不同的方法,但没有奏效。下面的示例 html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style type="text/css">

html, body { height: 100%; width: 100%; }
body { position: relative;  background-image:url('images/bg.jpg');background-repeat:repeat; }
#mydiv { 
    position: absolute;
    height: 100%;
    width: 100%;
    text-align:ceter;
}
</style>
</head>
<body>
</body>
</html>

回答by Aminah Nuraini

This CSS can center your image regardless of the length.

无论长度如何,此 CSS 都可以使您的图像居中。

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

The secret is in the transform. Without it, it only puts the top left pixel of the image in the center, not the whole image beautifully.

秘密就在transform. 没有它,它只会把图像的左上角像素放在中心,而不是整个图像漂亮。

回答by Matt Whitehead

Check this article out by Chris Coyier on CSS-Tricks. I think it might help out. I ran into the same problem a few days ago and his answer worked for me.

查看 Chris Coyier 关于 CSS-Tricks 的这篇文章。我认为它可能会有所帮助。几天前我遇到了同样的问题,他的回答对我有用。

Centering an image horizontally and vertically

水平和垂直居中图像

Basically the idea is, if your image has a set width and height. You can absolute position it from the left and top 50% and then do negative margins equal to half of the width and height to bring it back dead center. They're are other ways to vertically center an image if it doesn't have set dimensions.

基本上这个想法是,如果您的图像具有设定的宽度和高度。您可以将它从左侧和顶部 50% 绝对定位,然后做等于宽度和高度一半的负边距以将其带回死点。如果没有设置尺寸,它们是垂直居中图像的其他方法。

回答by KBN

You didn't have the ID set for the div, I have edited that, once that's done, the image will be horizontally aligned. Also, mydiv need not be positioned "absolute".

您没有为 div 设置 ID,我已经对其进行了编辑,一旦完成,图像将水平对齐。此外,mydiv 不需要定位为“绝对”。

To vertically align the picture, the best solution without using javascript would be to give the img a margin-top with %.

要垂直对齐图片,不使用 javascript 的最佳解决方案是为 img 设置一个带有 % 的边距顶部。

#mydiv {
 text-align: center;
}

#mydiv img {
 margin-top: 15%;
}