Given the following HTML:
<!doctype html>
<html>
<body>
<span style="background-color: blue;">
Some text here <br />
Some text here <br />
Some text here <br />
Some text here <br />
</span>
<div style="position: relative; background-color: lightblue;" id="first">
<div style="position: absolute; left: 180px; background-color: green;" id="second">
This is an absolutely positioned div within a div relative to the page.
</div>
</div>
<div style="background-color: red;" id="last">This is now positioned behind.</div>
</body>
</html>
(written for illustration purposes only).
Is there any way to make the flow of the document reset such that the div with id 'last' appears in flow with the rest of the document, after the absolutely positioned div (not behind). Without embedding it inside the divs with ids 'first' or 'second'.
I need to keep the general layout similar to this. But I don't want to have to use javascript to hackily position anything.
Any ideas or something I'm missing?
The #last element isn't actually behind #first. It's below it, but #first has 0 height because its only child is pulled out of the document flow by absolute positioning.
Would a different approach serve your needs?
Here are a couple of examples: http://codepen.io/Ghodmode/pen/diqcD
You didn't exactly explain what you need to do, or why #second needs to be absolutely positioned. We might be able to provide a better solution with a little more information.
In answer to the question of positioning something following a div whose contents are variable (and hence a variable height), I used the following code to position my controls div following a variable-height middle div. I wouldn't consider it a 'hack', since the browser doesn't know at load time how high the middle div is.
The $('#middleDiv').load(xxx) dynamically loads in the HTML snippet I want to display on the page. Since load is asynchronous I have a completion anonymous function to calculate the top of the controls div. Within the dynamic HTML I have a single article element which I can use to calculate the height of the dynamic content - $('article').height.
The second part of the calculation subtracts half the height of the controls to position it just below my content.
The CSS must use relative positioning for this to work:
The controls on this page are simple, just a button. I added a bottom margin to leave a bit of whitespace following the controls.
I happened to use an absolute position for the article element itself, although I am sure it would also work with a position:relative element.
One way would be to add a
height
rule to#first
using css, making#first
taller than#second
and forcing#last
out from underneath#second
. That would be the easiest way I can think of. Does this help?First-- why does #second need to be absolutely positioned?
To maintain document flow you should have a height property on both #first and #second, and make sure the height on #first is greater than or equal to the height of #second