2016-08-27 34 views
3

我有一個圖像設置爲left: 50%;。然而,它的右邊距離太遠,就像選擇器不在中間位置,而是在左邊。圖像不以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> 
+1

這裏的答案和解釋:http://stackoverflow.com/q/36817249/3597276 –

回答

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>

+0

由於一噸!完美的作品 –

+1

歡迎您,所以可以讓這個成爲檢查答案:-) – nvl

+1

我會一次5分鐘的時間結束。 :) –

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>

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>

+1

大家都知道,['calc()'在80年代的低端市場上擁有全球支持。](http://caniuse.com/#search=calc)(〜83.46%) –