You don’t need JavaScript
to maintain the ratio between Width
and Height
, if you want to keep the Height
commensurate with Width
, set the Height
with vw (viewport width)
.
If you need Width to be proportional to Height, set the Width
with vh (viewport height)
.
How do you want a perfect square, ie a ratio of 1:1, then the vw
of height
will equal %
of width
.
Follow 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>
The
width()
does not return the percentage but the width of the element inpx
even if it is defined in%
.– Filipe Moraes
@Filipemoraes the element is 465px wide, set to 32% width, and when I give console.log it returns 32px
– Murilo Melo
see here an example: https://jsfiddle.net/pueogbxx/1/ your problem must be different. The code that is in the question, is the code used in the project or is it just an example? Ask your question your HTML too.
– Filipe Moraes
is the code used
– Murilo Melo
Murilo, take the images and put as text formatted as code, with images we cannot copy the code.
– Filipe Moraes