An alternative to absolute positioning that updates parent height

I am working on a library that draws brackets.

I calculate the coordinates of each element (matches and strings) using javascript. Each element has position: absolute;and uses leftboth topto set the coordinates xand y.

As I use position: absolute;, it is necessary to set the parent element position: relative;so that the children are positioned relative to their parent.

enter image description here

This worked fine until I noticed that the height of the parents was not updated in his children, because the elements position: absolute;are pulled out of the document stream.

I need the parent to have a height so that I can put other elements under it and give parent styles, such as background-color...

  • , x y, , width height ?

  • , , javascript ( jQuery ), div. , width height javascript.

  • position: relative; position: absolute;, , , , . , , , , .

enter image description here

  1. , , . javascript, scrollHeight height , document, document.body window. , undefined, .

, body height 2500px, , - . , , .

<div class="BrackChart_wrapper">
    <div class="BrackChart_match"> ... </div>
    <div class="BrackChart_line"></div>
    etc.
</div>

.BrackChart_wrapper {
    position: relative;
    top: 0px;
    left: 0px;
}

.BrackChart_match, .BrackChart_line {
    position: absolute;
}

, !

JSFiddle: https://jsfiddle.net/jmjcocq8/1/

: https://jsfiddle.net/jmjcocq8/2/

+4
1

, , ( ) , .

, , , y .

, , :

var forEach = Array.prototype.forEach;
function positionChildren(parent) {
  var left = 0;
  var top = 0;
  forEach.call(parent.children, function(child, index) {
    child.style.left = left + "px";
    child.style.top = top + "px";
    left += 20;
    top += 10;
  });
  var height = top - 10 + 1 + parent.lastElementChild.clientHeight;
  console.log("height = " + height);
  parent.style.height = height + "px";
}

positionChildren(document.getElementById("parent"));
#parent {
  border: 1px solid black;
  background-color: #ddd;
  position: relative;
}
.child {
  position: absolute;
  border: 1px solid blue;
  padding: 0;
  margin: 0;
}
<div id="parent">
  <div class="child">Child1</div>
  <div class="child">Child2</div>
  <div class="child">Child3</div>
</div>
Hide result
+2

Source: https://habr.com/ru/post/1682020/


All Articles