Taking the total in pixels of an element passed as a percentage variable

0

I am setting a% w_th of% that should be an exact square, but this square should be based on the% w_th of% that is being set with% w_th of% (%), / p>

EX: 5% = 105px

var larguraVideoItemFirst = $('.video-item-first').width()//retorna 5 pois foi setado 5%.
$('.video-item-first').css({'height':larguraVideoItemFirst + 'px'}); //converte usando os 5% como pixel, ficando 5px.
    
asked by anonymous 23.01.2017 / 14:55

2 answers

5

You do not need JavaScript to maintain the ratio of Width to Height , if you want to keep Height proportional to Width , set Height with vw (viewport width) .

If you need Width to be proportional to Height, set Width to vh (viewport height) .

As you want a perfect square, that is, a ratio of 1: 1, then the vw of height will be equal to % of width .

Here is an example below:

.bloco {
  float: left;  
}

.bloco20 {
  background-color: teal;
  width: 19%;
  height: 19vw;
  margin: 0.5%;
}

.bloco40 {
  background-color: crimson;
  width: 39%;
  height: 39vw;
  margin: 0.5%;
}
<div class="bloco bloco20"></div>
<div class="bloco bloco20"></div>
<div class="bloco bloco20"></div>
<div class="bloco bloco20"></div>
<div class="bloco bloco20"></div>
<div class="bloco bloco40"></div>
<div class="bloco bloco40"></div>
<div class="bloco bloco20"></div>
<div class="bloco bloco20"></div>
    
23.01.2017 / 15:11
2

The width method gets the current computed width of the element in question (see the jQuey documentation ).

Then the value of $('.video-item-first').width() will be px and not percentage.

Chrome has the element inspector , use it and see what element has width rendered in px .

See the example below, I have determined that the width of the element will be 30% , but the width method returns the value in px :

$(document).ready(function(){
  var $quadrado = $('.quadrado');
	var w = $quadrado.width();
  
  $quadrado.height(w + 'px');
  $quadrado.html("O quadrado tem " + w + "px de largura.");  
});
.quadrado {
  display:block;
  float:left;
  width: 30%;
  height: auto;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="quadrado"></div>

Cases where the value may not match the width of the rendered element or match the value in percentage:

  • The parent element has 100px width and the width in px will match the value in % .
  • When using the class property, the width method returns the value corresponding to the first found element (see an example ), so the second element may have a second class (or inline style ) that modifies the width by implying that the calculation is wrong.
  • The javascript is executed before rendering the element.
  • JQuery (v3.1.1) returns the percentage if you check the value very early (when the DOM is not yet ready) and in your CSS you have specified a percentage.
23.01.2017 / 15:14