Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make absolute positioned elements move with the rest of the page?

When I absolute position an object, it is stuck there. When you resize the browser window, it stays there while the other objects slide around, thus killing the whole point.

Now this is only for me. Obviously it works on normal websites, such as the one your on right now. when you resize the window everything moves around and stays in its overall template.

How can I achieve this with absolute positioning?

like image 641
roozbubu Avatar asked Oct 09 '11 20:10

roozbubu


People also ask

How do you move elements with absolute position?

Absolute Positioning You can use two values top and left along with the position property to move an HTML element anywhere in the HTML document. Move Left - Use a negative value for left. Move Right - Use a positive value for left. Move Up - Use a negative value for top.

How does setting position absolute on an element affect where it appears on the page?

Absolutely positioned elements are removed entirely from the document flow. That means they have no effect at all on their parent element or on the elements that occur after them in the source code. An absolutely positioned element will therefore overlap other content unless you take action to prevent it.

Which position will keep the element in the same place regardless of scrolling?

A fixed position element is positioned relative to the viewport, or the browser window itself. The viewport doesn't change when the window is scrolled, so a fixed positioned element will stay right where it is when the page is scrolled.


2 Answers

You need to put the absolutely positioned div inside a relatively position div. Anytime the relatively positioned div moves, the absolute positioned div will also move with it.

<div class="relative" >
    <div class="absolute">absolute</div>
</div>

.relative{
    position:relative;
    top:100px;
    left:100px;
    width:500px;
    height:500px;
    background:blue;
}


.absolute{
    position:absolute;
    width:100px;
    height:100px;
    background:red;
    top:30px;
    left:50px;
}

Check working example at http://jsfiddle.net/w2EMu/

like image 156
Hussein Avatar answered Nov 15 '22 19:11

Hussein


The best solution would be to avoid absolute positioning. But if you use it and want to reposition your absolute object you could register a resize method. E.g. jQuery.resize() and reposition it yourself. If you are not using jQuery you have to use document.addEventListener and document.attachEvent.

like image 41
styrr Avatar answered Nov 15 '22 21:11

styrr