I have a JS library, Vega, that given a div attaches a series of child divs representing UI elements concluding in a final canvas element. The problem is the canvas element will overflow and I'm trying to center it within the given div. I've provided a MWE that distills all my requirements.
Align the green box with the grey box with the following requirements:
parentincluding padding has the same width asuser-div***elementhas the same width asparentexcludingparent's paddingchildis centered relative touser-div(orparentincluding padding)user-divfits to the height ofchild
*** Technically parent may be smaller as long as element does not change width and parent remains right-aligned, see below.
user-div is used for positioning and sizing parent. parent is given to the JS library and will contain a UI element in the padding (set via JS) that must be within and right-aligned to user-div. The width of element determines the width of the child canvas, so the width of element must not be changed. child overflows and should be centered within user-div.
/* Requirements:
* parent including padding has the same width as user-div
* element has the same width as parent excluding parent's padding
* child is centered relative to user-div (or parent including padding)
* user-div fits to the height of child
*/
.user-div {
/* Uncomment height to visualize boxes
height: 10em;
*/
width: 10em;
background: grey;
margin-left: 10em;
padding: 1em;
}
/* unknown: padding-right specified by library
* requirement: width specified by user
*/
.js-parent {
/*
*/
position: relative;
width: 100%;
height: 100%;
background: red;
padding-right: 2em;
box-sizing: border-box;
}
.js-element {
/*
position: absolute;
position: relative;
width: 100%;
right: 0;
position: initial !important;
*/
height: 90%;
background: blue;
}
/* unknown: width and height specified by library
*/
.js-child {
/*
position: absolute;
*/
position: relative;
width: 15em;
height: 2em;
background: green;
margin-left: 50%;
transform: translateX(-50%);
}
.test-bounds {
background: orange;
width: 30em;
}
<div class="test-bounds">Above</div>
<div class="user-div">
<div class="js-parent">
<div class="js-element">
<div class="js-child">
</div>
</div>
</div>
</div>
<div class="test-bounds">Below</div>
You can see from my comments that I've come up (with some help) with 2 partial solutions with drawbacks. For example, absolute child means user-div collapses vertically. Absolute element also increases the width of element breaking the JS library. Both approaches explore removing elements from the flow. An alternative is to undo the padding of parent in element but I haven't figured any approach