简体   繁体   中英

Percent Position CSS/ Javascript

If Have a div say

<div style="position:absolute;top:0%;left:94%;width:40px;height:40px;"/>

when viewed on different screen resolution the 94% starts to slide to the right, is that normal behavior.

The div is relative to the document, so when the window resize's , I want it to move along with the window.

I hope I am making sense. As I have it right now, it stays close to where I placed it, but as the screen gets larger or the doc is viewed on a higher resolution, it starts to shift.

Question : How can I position a div absolutely with percents and keep it in the correct position when the screen size/ resolution changes.

Edit: Here is what I am trying to do. I am writing an application in which a user can pick some items from a tool box, drag and drop onto a window sort of like Visual Studio, except the result is not a form its an HTML page. I got all this working and it works just fine. My problem started when I started testing on different screens and resolutions the end result is always different from the screen the user used to create the html page. Every thing in the page is absolutely positioned except the main content area which is relative, it contains all the absolutely positioned Items.

What I had tried was the percent left and top values for the items on the screen, and that was what lead to my original question, at the suggestion of calculating my own values I tried this

var currH = $(window).height();
var currW = $(window).width();

var rW = currW / OrgWidth; //Orignal Width of the window when the item was placed

var rH = currH / OrgHeight; //Orginal height of the window when the item was placed 

var x =$("#Button_Tools").offset().left * rW;
var y =$("#Button_Tools").offset().top * rH;

$("#Button_Tools").css("left", x.toString() + "px");
$("#Button_Tools").css("top", y.toString() + "px");

I calculate this when the window first loads to and it moves the button to the exact same location the percent value moved it to.

What am I doing wrong? Any Takers.

You can't position a div absolutely with percents and expect it to behave the same in every screen. Since you are using percentage, the value will be proportional to the size of the screen. 94% of 1000 is different than 94% of 1500.

You can set the right attribute instead of the left, something like:

<div style="position:absolute;top:0%;right:20px;width:40px;height:40px;"/>

You could also compute this value in the page load event based on the current width of the page, this way you guarantee that the position will be the same even when the window is resized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM