Search code examples
javascripthtmlcsscss-transforms

How to fit HTML parent element's bounding box to a CSS transformed child?


Is there a way, preferably without using JS, to make the container in following code snippet to wrap the scaled, and more generically, transformed child element, i.e. solid red outer border fully contains dashed blue border?

BTW, this appears to be a browser bug as it violates the default box model behavior that parent's size is auto adjusted to fit children.

#container {
  border: 1px solid red;
}

#scaled {
  border: 1px dashed blue;
  transform: scale(3, 3);
  transform-origin: 0 0;
}
<div id="container">
  container
  <div id="scaled">
    scaled 3x
  </div>
</div>


Solution

  • There is no way to do this without using JavaScript, but it is also not a browser bug. CSS transforms happen in the graphics pipeline, after the page flow is calculated and every non-transformed element's position and size are determined.

    This means that CSS transforms do not cause the size of any other element to be recalculated, and that is why the container is not being resized to contain the transformed child element. This is actually a feature of transform meant to improve performance by avoiding layout recalculation entirely.

    The only way you can do this cleanly is to apply the transform to the parent element, which it seems like you're trying to get away from. If you want it to be dynamic, and you want to stay away from JS, there is unfortunately no other way.

    #container {
      border: 1px solid red;
      transform: scale(3, 3);
      transform-origin: 0 0;
    }
    
    #scaled {
      border: 1px dashed blue;
      
    }
    <div id="container">
      container
      <div id="scaled">
        scaled 3x
      </div>
    </div>