Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Div Positioning After Absolute Div

Tags:

html

css

What is the best way for me to resume the flow of the page in css.

Here is my situation:

I have 3 divs div 1(parent), div 1(child), and div 2(normal). parent div is absolute, child is relative. All is good so far. The problem i'm having is the the next normal div is shifted up to the same line as the absolute div (since i disrupted the flow of the page setting the parent div to absolute).

So my question is how do I put the normal div under the div that has the position of absolute. Do I just offset the margin-top property?

Thanks for all the help!

Take a look: https://jsfiddle.net/veLgmdt1/

like image 934
max234435 Avatar asked Dec 18 '25 06:12

max234435


1 Answers

If you know the height of the absolute-positioned element, it would be easy. Simply add padding / margin or placeholder div equal to the known height.

If the height is dynamic, you'd have to resort to jQuery/JavaScript.

Have a look at my demo which shows the default behaviour and the methods mentioned:

// get the absolute-positioned element
var abs = $("#dynamic .absolute");

// get height of absolute-positioned element
var absHeight = abs.height();

// insert placeholder div with height equal to absolute-positioned element
$("<div class='placeholder'></div>").height(absHeight).insertAfter(abs);
section {
  position: relative;
  padding: 1em;
  margin: 1em;
  border: 1px solid #CCC;
}

section div {
  border: 1px dashed blue;
}

.absolute {
  position: absolute;
  top: 0;  z-index: 1;
  border:1px solid red;
  height:50px;
}

#margin .absolute+div {
  margin-top:50px;
}

#padding .absolute+div {
  margin-top:50px;
}

.placeholder { height:50px; border:none }

#dynamic .absolute {
  height:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Default Behaviour</h3>
<section>
  <div class="absolute">position:absolute</div>
  <div>normal div</div>
</section>

<h3>Known height: top margin</h3>
<section id="margin">
  <div class="absolute">position:absolute</div>
  <div>normal div with margin-top</div>
</section>

<h3>Known height: top padding</h3>
<section id="padding">
  <div class="absolute">position:absolute</div>
  <div>normal div with padding-top</div>
</section>

<h3>Known height: placeholder div</h3>
<section>
  <div class="absolute">position:absolute</div>
  <div class="placeholder"></div>
  <div>normal div</div>
</section>

<h3>Dynamic height: JavaScript/jQuery</h3>
<section id="dynamic">
  <div class="absolute">position:absolute</div>
  <div>normal div</div>
</section>

jsFiddle: https://jsfiddle.net/azizn/mq6bejhf/

like image 62
Aziz Avatar answered Dec 20 '25 20:12

Aziz