How to set the height and width of a SVG element to the scrollHeight and scrollWidth of its parent DIV?

Viewed 34

I have a #frame DIV of a fixed size. In this #frame is a #scrollable DIV. In the #scrollable are different #item DIVs with absolute position. They exceed the width and height of the #scrollable, so the scrollWidth and scrollHeight gets bigger than its width and height. Now I want to put a SVG as a #background into the #scrollable. The #background should have the same size as the #scrollable. I have defined the SVG with width=100% and height=100%. But this does not match the scrollWidth and scrollHeight. You can see this in the example, because there is still a red area. My aim was to make the #background as big as the #scrollable so that the red area disappears and gets yellow. But it did not work. How to get this working?

#frame {
  width: 20em;
  height: 10em;
  border: 1px solid black;
}

#scrollable {
  min-width: 100%;
  min-height: 100%;
  overflow: scroll;
  position: relative;
  background: rgb(255,0,0,0.2);
}

#background {
  background: rgba(0,255,0,0.2);
}

#item {
  position: absolute;
  top: 5em;
  left: 15em;
  min-height: 10em;
  min-width: 10em;
  background: rgba(0,0,255,0.2);
  border: 1px solid rgb(0,0,255);
}
<div id="frame">
  <div id="scrollable">
    <svg id="background" width="100%" height="100%"></svg>
    <div id="item"></div>
  </div>
</div>

1 Answers

So you need to stack items on top of each other and have the container automatically resize to fit all the items.

An alternative to position: absolute is to use grid layout and put everything in the same grid cell, and instead of top/left, you use margins to position each item (taken from this answer).

#frame {
  width: 20em;
  height: 10em;
  border: 1px solid black;
}

#scrollable {
  width: 100%;
  height: 100%;
  overflow: scroll;
  background: rgb(255,0,0,0.2);

  display: grid;
}
#scrollable > * {
  /* Stack all elements on top of each other in a single cell: */
  grid-area: 1/1;
  /* Don't stretch elements to fill the cell: */
  justify-self: start;
  align-self: start;
}

#background {
  background: rgba(0,255,0,0.2);
}

.item {
  min-height: 10em;
  min-width: 10em;
  background: rgba(0,0,255,0.2);
  border: 1px solid rgb(0,0,255);
}
#item-1 {
  margin-top: 5em;
  margin-left: 15em;
}
#item-2 {
  margin-top: 7em;
  margin-left: 7em;
}
#item-3 {
  margin-top: 10em;
  margin-left: 20em;
}
<div id="frame">
  <div id="scrollable">
    <svg id="background" width="100%" height="100%" viewBox="0 0 10 10"></svg>
    <div id="item-1" class="item"></div>
    <div id="item-2" class="item"></div>
    <div id="item-3" class="item"></div>
  </div>
</div>

Related