Scaling any HTML Element

Sometimes while styling a responsive website you encounter layouts where you are not able to easily make it scalable. If you ever have part of a document with a set width and height, this technique can help you make it scalable based on a simple formula for the scaling factor: scale = desiredwidth / nativeWidth

Parts Required

CSS Code

.wrapper {
  width: 100%;
  height: calc(var(--wrapper) * 1px);
}
.wrapper .element {
  --originalWidth: 500;
  position: absolute;
  top: 50%;
  left: 50%;
  transform:
    translateX(-50%)
    translateY(-50%)
    scale(calc(var(--wrapper) / var(--originalWidth)))
  ;
}

JS Tests

How to expose the current wrapper.offsetWidth as a CSS variable named var(--wrapper):

var element = document.querySelectorAll('.wrapper')

for (var i=0; i<element.length; i++) {

  element[i].style.setProperty('--wrapper', element.offsetWidth)

}

Plugins Capable

Syntax Example

EQCSS

@element .wrapper {
  $this {
    width: 100%;
    height: eval("offsetWidth")px;
  }
  $this .element {
    position: absolute;
    top: 50%;
    left: 50%;
    transform:
      translateX(-50%)
      translateY(-50%)
      scale(eval("offsetWidth / 500"))
    ;
  }
}

Varsity

#wrapper {
  width: 100%;
  height: calc(var(--wrapper-offsetWidth) * 1px);
}
#wrapper aside {
  position: absolute;
  top: 50%;
  left: 50%;
  transform:
    translateX(-50%)
    translateY(-50%)
    scale(calc(var(--wrapper-offsetWidth) / 500))
  ;
}

reproCSS + Scoped Eval() Mixin

<style process=auto>
  ${scoped('.wrapper', `
    --offsetWidth: eval(this.offsetWidth);
    width: 100%;
    height: calc(var(--offsetWidth) * 1px);
  `)}
  ${scoped('.wrapper .element', `
    position: absolute;
    top: 50%;
    left: 50%;
    transform:
      translateX(-50%)
      translateY(-50%)
      scale(calc(var(--offsetWidth) / 500))
    ;
  `)}
</style>

Demos

Further Reading