March 6, 2012

Shift centred div to the right

Question by Vince Lowe

I have a div called target which is centred and displayed over a google map when you pan to a map marker, i have since added a menu to the left of the map which means that when the google map pans to a marker it is no longer the centre of the screen.

I need to move the div to the right but I can’t seem to move it.

#target {
    position: fixed; 
    display: none; 
    width: 51px; 
    height: 51px; 
    top: 50%; 
    left: 50%; 
    margin: -40px 0 0 -26px; 
    background: url(../img/target.png) no-repeat center bottom; 
    z-index: 2;
}

Screenshot

Answer by Daniel K

You should be able to rectify your problem by playing a bit with the margin. Change the 4th value by adding a positive value so that it is greater than -26px. Such as:margin: -40px 0 0 20px;.

The 4th value in margin specifies the left margin value, which will shift your div to the right.

Alternatively

You can wrap the map and target div in a separate div from the menu, but you must change the target position value to relative or absolute instead of fixed:

<body>
    <div id="wrapper" style="position:relative;"> <!-- map and target wrapper div. make sure this is position: absolute OR relative so that positioning will reference this div. -->
        <div id="map">...</div>
        <div id="target"></div>
    </div>

    <div id="menu">
        ...
    </div>
</body>

With this alternate solution, the target and the map are aligned to the same div, almost as if they’re in their own window.

Answer by Starx

With your CSS, it is not possible to shift to the right. As it is what is forcing it to center

position: fixed;
left: 50%; /* be in the center */
top: 50%;

In order to change the position to the right, remove the left property and update you css to read the following.

right: 0;
top: 50%;

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!