Как привязать высоту блока к его ширине? (не к ширине окна, а именно ширине блока)
2 ответа
С помощью 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>
С помощью 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>
Еще можно поставить "распорку" в виде 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>