我怎样才能完美地居中我的形象?

How can I perfectly center my image?

所以我的网站上有一张图片,我想将它完美居中。我尝试了很多东西,但 none 奏效了。

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
}
<img src="images/astronaut.png">

像这样?

body{
background-color: black;
}

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5;
  left: 50%;
  top:50%;
  transform: translate(-50%, -50%);
}
<img src="images/astronaut.png">

居中代码是lefttop,尤其是transform

将图像水平居中的最简单方法是:

img {
    display: block;
    margin-right: auto;
    margin-left: auto;
}

查看以下链接以获得更多帮助,希望对您有所帮助。

https://www.w3.org/Style/Examples/007/center

https://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/

html { 
  width: 100%; 
  height: 100%; 
  background:url(http://tse4.mm.bing.net/th?id=OIP.IX1fAIIUJ82DtdfgR2tSnADhEs&w=207&h=276&c=8&qlt=90&o=4&dpr=2&pid=1.7) center center no-repeat;
}

如果您的位置未设置或设置为相对位置,将左右边距设置为自动将使图像在其父级内水平居中。

所以你可以使用:

img {
  margin-top: 10%;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
  height: 40%;
  z-index: -5
}

如果您的位置需要设置为绝对位置,您可以使用 CSS3 的视口大小调整使图像居中。这会将图像放在页面的正中央;因此,例如,如果您想将侧边栏中的图像居中,请不要使用此方法。您需要为图像设置宽度,然后使用 "left" 属性 对齐它。看起来像这样:

img {
  position: absolute;
  margin-top: 10%;
  text-align: center;
  height: 40%;
  z-index: -5
  width: 500px;
  left: calc( 50vw - 250px );
}

视口始终为 100vw 宽,因此将左侧 属性 设置为 50vw - 图像宽度的 1/2 将使它在页面上居中。

您也可以使用 jQuery 类似地计算正确的对齐方式并定位元素。

您可以将图片放在 div 中,并使其在宽度和高度上占屏幕的 100%。
然后添加 text-align:center;使其水平居中。
然后设置行高为100%然后加上vertical-align: middle;到图像以使其垂直居中。

body{
background-color: black;
}

   .CenterImage img {

  height: 40%;
  z-index: -5;
vertical-align: middle;

}
.CenterImage{
width:100vw;
height:100vh;
line-height: 100vh;
text-align:center;
}
<div class="CenterImage"><img src="images/astronaut.png"></div>

body{
background-color: black;
}

img {
  position: absolute;
  text-align: center;
  height: 40%;
  top: 50%;
  left: 50%;
  z-index: -5
}
<img src="images/astronaut.png">