2

I have a div inside another div with transform scale applied.

I need to get the width of this div after the scale has been applied. The result of .width() is the original width of the element.

Please see this codepen: https://codepen.io/anon/pen/ZMpBMP

Image of problem:

enter image description here

Hope this is clear enough, thank you. Code below:


HTML

<div class="outer">
  <div class="inner">
  </div>
</div>

CSS

.outer {
  height: 250px;
  width: 250px;
  background-color: red;
  position: relative;
  overflow: hidden;
}

.inner {
  background-color: green;
  height: 10px;
  width: 10px;
  transform: translate(-50%);
  position: absolute;
  top: 50%;
  left: 50%;

  transform: scale(13.0);
}

JS

$(function() {

   var width = $('.inner').width();

   // I expect 130px but it returns 10px
   //
   // I.e. It ignores the zoom/scale
   //      when considering the width
   console.log( width );

});
Jack
  • 3,271
  • 11
  • 48
  • 57
  • Possible duplicate of [Retrieve width/height of a css3 scaled element](https://stackoverflow.com/questions/5834624/retrieve-width-height-of-a-css3-scaled-element) – insertusernamehere Aug 29 '18 at 06:15

3 Answers3

2

Use getBoundingClientRect()

$(function() {

   var width = $('.inner')[0].getBoundingClientRect();
   // I expect 130px but it returns 10px
   //
   // I.e. It ignores the zoom/scale
   //      when considering the width
   console.log(width.width);

});

https://jsfiddle.net/3aezfvup/3/

Pingu69
  • 36
  • 5
1

You need the calculated value. This can be done in CSS.

Use calc() to calculate the width of a <div> element which could be any elements:

#div1 {
    position: absolute;
    left: 50px;
    width: calc(100% - 100px);
    border: 1px solid black;
    background-color: yellow;
    padding: 5px;
    text-align: center;
}

I found this about this topic.

Can i use Calc inside Transform:Scale function in CSS?


For JS:

How do I retrieve an HTML element's actual width and height?

Simon Jensen
  • 287
  • 5
  • 24
  • I'm sorry, I'm trying to get the width of the inside green box element in JS not css – Jack Aug 29 '18 at 06:16
1

i achieved your 130 by this

var x = document. getElementsByClassName('inner');
var v = x.getBoundingClientRect();
width = v.width;
BardZH
  • 402
  • 2
  • 6
  • 21