Div图像不是垂直和水平居中?

时间:2017-03-14 03:16:44

标签: html image centering

无论我尝试什么,我的图像都不会与顶部的标题对齐。 如果有人能为我提供代码更正,我们将不胜感激。提前谢谢。



img {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 675px;
  height: 418px;
  margin-top: -250px;
  /* Half the height */
  margin-left: -250px;
  /* Half the width */
}

body {
  background-color: black;
}

h1 {
  color: white;
  text-align: center;
}

p {
  color: white;
  font-family: verdana;
  font-size: 20px;
}

<h1>Text</h1>
<div class="img">
  <img src="rsz_damon600.png">
</div>
&#13;
&#13;
&#13;

5 个答案:

答案 0 :(得分:1)

你应该将margin-top和margin-left设置为宽度和高度的一半。

或者如果您不知道元素的大小,可以使用

转换:翻译(-50%, - 50%);

垂直和水平居中

img {
   position: absolute;
   top: 50%;
   left: 50%;
   /* width: 675px;
   height: 418px; */
   transform: translate(-50%, -50%);
}

另一种方法:

img {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   bottom: 0;
   margin: auto;
}

这是guide

答案 1 :(得分:0)

尝试:

<!DOCTYPE html>
<html>
<head>
<title>HTML Reference</title>
<style>
img {
   display: block;
   margin: 0 auto;
}

body {
    background-color: black;
}

h1 {
    color: white;
    text-align: center;
}

p {
    color : white;
    font-family: verdana;
    font-size: 20px;
}
</style>
</head>
<body>

<h1>Text</h1>
<div class="img">
  <img src="rsz_damon600.png">
</div>

</body>
</html>

答案 2 :(得分:0)

使用css技巧transform: translate(-50%, -50%)

&#13;
&#13;
img {
   position: absolute;
   top: 50%;
   left: 50%;
   width: 675px;
   height: 418px;
   transform: translate(-50%, -50%);
}


body {
    background-color: black;
}

h1 {
    color: white;
    text-align: center;
}

p {
    color : white;
    font-family: verdana;
    font-size: 20px;
}
&#13;
<style>
</style>
<body>

<h1>Text</h1>
<div class="img">
  <img src="http://www.motorverso.com/wp-content/uploads/2015/01/iNFINITI-q60-1_1280x792-675x418.jpg">
</div>

</body>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

您可以像这样简单地做到这一点。将图像放置在div元素内。然后将div的边距设置为auto。 :)

<div name="my_div"style="margin:auto;">
      <img src="" id="" />
</div>

答案 4 :(得分:-1)

尝试将left:50%更改为left:43%。这应该可以让你到达你想去的地方。