Custom element with position absolute

1.6k views Asked by At

I am trying to contain/put a fin-hypergrid within a web component, but because it's scrollbars are custom divs with position: absolute on them, they are positioned absolute to the window rather that the component itself.

Here is my jsfiddle: https://jsfiddle.net/50kyyfam/

I'm almost certain I need to add a css properties to the :host style to tell the grid to position absolute to the boundary of the data-grid component, but I don't know what it should be?

EDIT: As a side note, if any of the fin-hypergrid are looking, the minified version of core threw an exception when initialising the above jsfiddle. (Chrome 63)

1

There are 1 answers

0
UncaughtTypeError On BEST ANSWER

To position an absolutely positioned element relative to its containing element, position: relative should be declared on that containing element, e.g:

data-grid {
    position: relative;
}

class DataGrid extends HTMLElement {

    constructor() {
      super();
      this.createShadowRoot().innerHTML = `
       <style>
         :host {
           display: block;
          }
          
          div {
           height: 100%;
           width: 100%;
          }
        </style>
        <div></div>
      `;
    }

    connectedCallback() {
   const grid = new fin.Hypergrid(this.shadowRoot.querySelector('div'));
      const data = [
        { name: 'Company 1', price: 300 },
        { name: 'Company 2', price: 200 },
        { name: 'Company 3', price: 150 },
        { name: 'Company 4', price: 500 },
        { name: 'Company 5', price: 999 }
      ];
      grid.setData(data);
    }

  }

  customElements.define('data-grid', DataGrid);
data-grid {
    position: relative;
}
<script src="https://fin-hypergrid.github.io/core/2.0.2/build/fin-hypergrid.js"></script>

<data-grid style="width:100px; height: 150px;"></data-grid>

Updated JSFiddle

To expand upon, for the sake of clarity and for the potential benefit of any other possible readers:

  • When declaring an element as an absolutely positioned element (absolute or fixed) you are removing the element from the natural document flow; which simply means the element is no longer interacting with sibling elements in the way relative or static elements do (imagine the element "siting above" the rest of the DOM).
  • By default, an absolutely positioned element's position is "relative" to the window; this means if you offset its position with left or right property values it'll move a distance equal to the property value from the window. You can position an element with a position property value of absolute (not fixed) relative to any containing element if you declare relative positioning to that containing element.