3

I have an image set to left: 50%;. However, it's a little too far to the right, like the selector is not in the center, but on the left side.

My CSS Code:

#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%;
}

My HTML Code:

<div id="scroll-down">
  <div id="scroll-arrow"></div>
</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
Matt.Owen
  • 391
  • 1
  • 4
  • 15

3 Answers3

2

To make the image exactly placed on center, you need to put some margin-left with value is minus half of your image width.

Please try this example

#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>
novalagung
  • 10,905
  • 4
  • 58
  • 82
2

Use transform: translate(-50%, 0) to center it horizontally.

(removed margin-top you had for scroll-down too for illustration)

#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>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
2

The image width is 64px so to make it exactly in the center, left value should be 50% - 32px.

Use: 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>
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • 1
    Just so everyone knows, [`calc()` has global support in the low 80s.](http://caniuse.com/#search=calc) (~83.46%) – J. Allan Aug 27 '16 at 04:08