Reputation: 391
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>
Upvotes: 3
Views: 690
Reputation: 11502
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>
Upvotes: 2
Reputation: 15501
The image width is 64px
so to make it exactly in the center, left
value should be 50% - 32px
.
Use: calc()
- CSS | MDN
#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>
Upvotes: 2
Reputation: 42352
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>
Upvotes: 2