How to tie the height of the block to its width ? (not to the width of the window, namely the width of the block)

Closed due to the fact that off-topic participants are Air , HamSter , Kromster , Arsen , 0xdb Mar 13 '18 at 1:21 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • β€œQuestions asking for help with debugging (β€œ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - Air, HamSter, 0xdb
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • var height = $ ("div"). height (); $ ("div"). css ({"width": height + "px"}); - Daniel
  • 3
    What do you need this for? (there are different approaches) - Yuri Kopot

2 answers 2

Using CSS

.ratio { width: 50%; /* здСсь ΠΌΠΎΠΆΠ½ΠΎ ΡƒΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π»ΡŽΠ±ΡƒΡŽ Π½ΡƒΠΆΠ½ΡƒΡŽ ΡˆΠΈΡ€ΠΈΠ½Ρƒ */ } .ratio-inner { position: relative; height: 0; border: none; } .ratio-content { position: absolute; top: 0; right: 0; bottom: 0; left: 0; background: #eee; } .ratio-4-3 { padding-top: 75%; /* Π‘ΠΎΠΎΡ‚Π½ΠΎΡˆΠ΅Π½ΠΈΠ΅ 4 ΠΊ 3 */ } .ratio-5-1 { padding-top: 20%; /* Π‘ΠΎΠΎΡ‚Π½ΠΎΡˆΠ΅Π½ΠΈΠ΅ 5 ΠΊ 1 */ } 
 <div class="ratio"> <div class="ratio-inner ratio-4-3"> <div class="ratio-content"> Π­Ρ‚ΠΎ содСрТимоС Π±Π»ΠΎΠΊΠ° 4/3 </div> </div> </div> <br> <div class="ratio"> <div class="ratio-inner ratio-5-1"> <div class="ratio-content"> Π­Ρ‚ΠΎ содСрТимоС Π±Π»ΠΎΠΊΠ° 5/1 </div> </div> </div> 

Using js

 $(function(){ $('.ratio').height($('.ratio').width()*0.75); // Π‘ΠΎΠΎΡ‚Π½ΠΎΡˆΠ΅Π½ΠΈΠ΅ 4 ΠΊ 3 $(window).resize(function(){ $('.ratio').height($('.ratio').width()*0.75); }); }); 
 .ratio { background: #eee; width: 50%; /* здСсь ΠΌΠΎΠΆΠ½ΠΎ ΡƒΡΡ‚Π°Π½ΠΎΠ²ΠΈΡ‚ΡŒ Π»ΡŽΠ±ΡƒΡŽ Π½ΡƒΠΆΠ½ΡƒΡŽ ΡˆΠΈΡ€ΠΈΠ½Ρƒ */ } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="ratio">Π­Ρ‚ΠΎ содСрТимоС Π±Π»ΠΎΠΊΠ° 4/3</div> 

    You can also put a "spacer" in the form of SVG

     .outer { background: #ddd; width: 400px; position: relative; } .inner { position: absolute; margin : auto; top: 0; bottom: 0; right: 0; left: 0; width: 100px; height: 100px; } 
     <div class="outer"> <svg viewBox="0 0 16 9"></svg> <div class="inner">16x9</div> </div>