【问题标题】:Image not centered with 50%图像未以 50% 为中心
【发布时间】:2017-01-03 18:38: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>

【问题讨论】:

标签: html css image css-position centering


【解决方案1】:

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

【讨论】:

  • 非常感谢!完美运行
  • 不客气,所以可以让它成为检查答案:-)
  • 我会在 5 分钟的时间结束后。 :)
【解决方案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>

【讨论】:

【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2014-03-12
    • 2014-03-18
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    相关资源
    最近更新 更多