图像不以50%为中心

时间:2016-08-27 03:59:18

标签: html css image css-position centering

我的图片设置为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>

3 个答案:

答案 0 :(得分:2)

要使图像准确放置在中心位置,您需要放置一些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>

答案 1 :(得分:2)

图片宽度为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>

答案 2 :(得分:1)

使用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>