content01 content01 - 1 year ago 73
HTML Question

How to keep elements in the same position when the browser is resized?

I have the following html:

<img id="myid" src='images/bigimage.png'/>
<div id="container">
<div id="fast-back">
<p class="big-font">SOMETHING</p>
<p class="small-font">SOMEThiNG ELSE</p>

And the CCS for it is:

html {
overflow-x: hidden;

body {
margin: 0;
padding: 0;
background: url(images/body-background.png) top no-repeat;
min-height: 860px;
height: 860px;

h1 {
margin: 0;
padding: 0;
position: absolute;
color: white;
visibility: hidden;
#container {
margin: 0 auto;
padding: 0;
position: relative;
min-width: 1336px;
height: 860px;
width: 1336px;
position: absolute;
left: 50%;
right: 50%;
margin-left: -1280px;
margin-right: -1280px;
z-index: 1004;
#fast-back {
position: relative;
margin-left: 15%; /*it moves even using pixel*/
top: 272px;
z-index: 99999;
text-align: center;
width: 126px;

However, when I resize the browser window, the "fast-back" div moves to the right.

How can I prevent this behaviour?


Answer Source

Looking at #fastback CSS rule, you are using percentage instead of pixels on margin-left. Change it to pixels as unit of measure.

If you are using percentage as unit of measure, the left margin of the element, in your case, will move in relation to the viewport.

And if you are using pixels, on the other hand, the margin stays on the same location, even if the browser is resized.


The solution is remove the width of the #container. See the following link.

The reason why the first solution does not work because the width of the container is set to 1336 pixels and centered aligned via margin: 0 auto. If the browser viewport width reaches beyond 1336 pixels during resize, the #fastback element will move.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download