图像未以 50% 居中

Image not centered with 50%

我有一个图像设置为 left: 50%;。不过有点太靠右了,好像选择器不在中间,而是在左边。

我的CSS代码:

#scroll-down {
  position: fixed;
  width: 100%;
  height: 64px;
  margin-top: -64px;
}

#scroll-arrow {
  position: absolute;
  background: url("img/down-arrow.png") center no-repeat;
  width: 64px;
  height: 64px;
  left: 50%;
}

我的HTML代码:

<div id="scroll-down">
  <div id="scroll-arrow"></div>
</div>

为了使图像准确地位于中心,您需要放置一些 margin-left,其值为 减去图像宽度的一半

请试试这个例子

#scroll-down {
    position: fixed;
    width: 100%;
    height: 64px;
}

#scroll-arrow {
    position: absolute;
    background: url("http://placehold.it/100x100") center no-repeat;
    width: 64px;
    height: 64px;
    left: 50%;
    margin-left: -32px; /* value -32px comes from (width / 2 * -1) */
}
<div id="scroll-down">
    <div id="scroll-arrow"></div>
</div>

使用 transform: translate(-50%, 0) 使其水平居中。

(删除了 margin-top 你为了 scroll-down 也为了说明)

#scroll-down {
  position: fixed;
  width: 100%;
  height: 64px;
}

#scroll-arrow {
  position: absolute;
  background: url("http://placehold.it/100x100") center no-repeat;
  width: 64px;
  height: 64px;
  left: 50%;
  transform: translate(-50%, 0);
}
<div id="scroll-down">
  <div id="scroll-arrow"></div>
</div>

图像宽度为64px,因此要使其正好位于中心,left 值应为50% - 32px

使用:calc() - CSS | MDN

calc() browser compatibility

#scroll-down {
  position: fixed;
  width: 100%;
  height: 64px;
  margin-top: -64px;
  border: 1px solid red;
}

#scroll-arrow {
  position: absolute;
  background: url("https://cdn2.hubspot.net/hub/31306/file-25644574-png/images/arrow_down1.png") center no-repeat;
  width: 64px;
  height: 64px;
  left:-webkit-calc(50% - 32px);
  left:-moz-calc(50% - 32px);
  left:calc(50% - 32px);  
  border: 1px solid black;
}
<div id="scroll-down">
  <div id="scroll-arrow"></div>
</div>