Felix Felix - 4 years ago 149
CSS Question

Prevent div overlapping in position:absolute div

By clicking a button we created a dynamic div using jquery .


$(".new-div").after('<div class="new-div" style="z-index:1; position:absolute;" >message</div>');


Currently what happen is , in webpage a new-div is already there , when clicking on the add-div then other new-div is created . The problem is the all new-div's are over lapped.
The message of one div is write over the message of other div .

How to solve this ?

I tried
margin-righ:auto; margin-left:auto ;

Here i cannot change position:absolute .Here
is a must one . So i am searching for a solution without changing position:absolute

Update : Please see this jsfiddle :

Thank you .

Answer Source

Please try this fiddle: https://jsfiddle.net/qqx1w1ef/4/

      var last_element = $('body').find('.new-div:last');
      var position_top = last_element.offset().top + last_element.outerHeight() + 10;
      $(".new-div:last").after('<div class="new-div" style="z-index:1; position:absolute; top: '+position_top+'px;">message</div>');

I made it right now, and it uses last element, and suming it position top + height, and adding 10 more pixels.

So you get absolute position, and always new append at last element.

Edited jsFiddle: https://jsfiddle.net/pmcqj50j/5/

To stop overflow you could use following css (fiddle updated too):

.parent-div { max-width: 236px; width: 236px; position: relative; overflow: hidden; }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download