Take measurements of an element and play in variables? How to do?

Asked

Viewed 2,143 times

5

Is there any way (using Sass maybe) to get the measurements (width and/or height) of already defined elements and store them in variables to use in calculations of other elements?

  • 2

    I believe that logic is the reverse: create variables, and then use to define the measures of all elements.

2 answers

3


Has by javascript. Using jQuery you can get the size of a div, for example, like:

var largura = $('div#id').width();

The height:

var altura = $('div#id').height();

0

Using the framework YUI 3 the solution is this:

var largura, altura;

YUI().use('node', function (Y) {
    largura = Y.one('div#meu-id').getComputedStyle('width');
    altura = Y.one('div#meu-id').getComputedStyle('height');
});

Using javascript only (Chrome, Firefox, Opera and Safari)

<style>
  div#meu-id  {
    height: 300px;
  }
</style>

<div id="meu-id">Meu conteúdo</div>

var RefDiv = document.getElementById("meu-id");
var largura = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("width");
var altura = document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("height");
setTimeout( function() { alert('largura = ' + largura + ', altura = ' + altura); }, 5000);

I used setTimeout in case there is code that changes the content of the element and so we give a time to render.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.