图像不会以边距居中:自动;

Image will not center with margin: auto;

我正在尝试为 TheOdinProject 上的作业重新创建 google 主页。如何让徽标贴在屏幕中央,两边的像素数量相等?

这是我的代码:

#logo {
  margin: auto;
  position: relative;
  display: block;
  width: 200px;
}
#searchbar {
  margin-left: 650px;
  position: relative;
  width: 1000px;
  line-height: 2;
}
<!DOCTYPE html>
<html>

<head>
  <title>Google Homepage Project</title>
  <link type="text/css" rel="stylesheet" href="stylesheet.css" />
</head>

<body>
  <div id="logo">
    <img src="http://fineprintnyc.com/images/blog/history-of-logos/google/google-logo.png">
  </div>
  <div id="searchbar">
    <form action="#" method="POST">
      <input type="text" name="searchbar">
    </form>
  </div>
</body>

</html>

#logo {
  margin: auto;
  position: relative;
  display: block;
  width: 200px;
}
#searchbar {
  margin-left: 650px;
  position: relative;
  width: 1000px;
  line-height: 2;
}

#logo img {
  max-width: 100%;
}
  <div id="logo">
    <img src="http://fineprintnyc.com/images/blog/history-of-logos/google/google-logo.png">
  </div>
  <div id="searchbar">
    <form action="#" method="POST">
      <input type="text" name="searchbar">
    </form>
  </div>

所以您有一个容器 div#logo,您指定了一个宽度为 200 像素的容器。然后你把一张图片放在里面,物理宽度为 570px。你在期待什么?

要解决它,请调整图像大小,或将此 css 分配给它:

#logo img { max-width: 100% }