Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does CSS3 right aligned background image appear in the wrong place?

I am using CSS3 background-position to position a background image 3% from the right edge of the container. However it appears in a different position compared to if i have an equivalent container that is 97% wide with the background image right aligned. You can see what i mean at http://jsfiddle.net/deshg/9qveqdcu/2/, the logo in the black row is further to the right than the one in the green row but surely they should be in the same horizontal position?

If anyone could shed some light on why this is happening it would be massively appreciated.

For reference, code is below.

Thanks all!

#container {
width: 100%;
background-color: #ffcc00;
}

#d1 {
background-color: #cccc00;
background-image: url('http://jsfiddle.net/img/logo.png');
background-position: right 3% center;
background-repeat: no-repeat;
width: 100%;
}

#d2 {
background-color: #000000;
color: #ffffff;
background-image: url('http://jsfiddle.net/img/logo.png');
background-position: right center;
background-repeat: no-repeat;
width: 97%;
margin-right: 3%;
}

<div id="container">
    <div id="d1">
        abvc
    </div>
    <div id="d2">
        def
    </div>
</div>
like image 545
deshg Avatar asked May 28 '15 11:05

deshg


2 Answers

The background image itself is being offset 3% of it's own width

From the docs:

Percentages refer to the size of the background positioning area minus size of background image; size refers to the width for horizontal offsets and to the height for vertical offsets

Here's an illustration when using 25% 25% (from CSS Tricks):

enter image description here

like image 64
Alex Avatar answered Oct 11 '22 16:10

Alex


Background position is not working as you thinking.

It's different than if you, say, had an and positioned it at left: 50%; in that scenario, the left edge of the image would be at the halfway point. If you want to center it, you'll need to pull it back to the left (negative translate or negative margin)

For better understanding refer Link And Link

For what you trying to achieve you have to set

background-position: 96% 0px, center center;

Fiddle

like image 38
ketan Avatar answered Oct 11 '22 15:10

ketan