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
- var height = $ ("div"). height (); $ ("div"). css ({"width": height + "px"}); - Daniel
- 3What do you need this for? (there are different approaches) - Yuri Kopot
|
2 answers
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> |