Search code examples
javascriptscalecss-transforms

Can you define a maximum width/height to CSS transform scale?


The following code scales the inner width to 100px.

But if the outer width is dynamic, is there a way to make sure the scaled inner width will not exceed 50px?

Kind of like max-width for scaling.

.outer {width: 200px; height: 100px; background-color: yellow;  position: relative}
.inner {transform: scale(0.5); background-color: red; transform-origin: center center;}
<div class="outer">
  <div class="inner">&nbsp;</div>
</div>


Solution

  • Transform isn't needed for here. Depending on what your actual situation is, you can use width: 50%; max-width: 50px; margin: 0 auto; to achieve better results and lose the transform and transform-origin:

    .outer {width: 200px; height: 100px; background-color: yellow;  position: relative}
    .inner {width: 50%; max-width: 50px; margin: 0 auto; background-color: red;}
    <div class="outer">
      <div class="inner">&nbsp;</div>
    </div>

    Furthermore, transform changes the visual formatting model and doesn't contain max-width settings you're looking for. You can achieve similar results with a series of @media queries to target specific sizes but you're already building responsive code so continue with percent-based widths.