I want to keep an aspect ratio on an absolute positioned div with auto dimensions. I tried some solutions from other stackoverflow questions, but they don't work or they need fixed dimensions.
I would like the div to wrap its content while maintaining a 4:3 ratio. I would like to solve it with css and less javascript.
Is there a clever way to do this with css?
My code is below.
$('span').hover(function() {
$(this).find('div').css('visibility', 'visible')
}, function() {
$(this).find('div').css('visibility', '')
})
.jsmbox {
position: absolute;
overflow: hidden;
-webkit-transition: all .3s ease;
transition: all .3s ease;
max-width: 100%;
max-height: 100%;
color: black;
background-color: gold;
padding: 6px;
visibility: hidden;
top: 0;
left: 0;
cursor: default;
text-align: justify;
z-index: 100;
}
.jsmbox:hover {
max-width: 400px;
max-height: 300px;
}
.custom {
width: 320px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span style="position: relative">[hover me1]
<div class="jsmbox">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ullamcorper eleifend augue, at eleifend lacus tincidunt sed. Nam et ipsum non dui pellentesque suscipit at finibus metus. Nullam vel augue eros. Sed sodales mi ut sodales posuere. Nullam eleifend nisl vel urna bibendum egestas. Sed eget dolor nunc. Curabitur elementum dolor sit amet enim pellentesque, vitae cursus tellus tempus. Maecenas non cursus nisl, sit amet volutpat nisl. Integer faucibus at nunc eget euismod.
</div>
</span>
<span style="position: relative">[hover me2]
<div class="jsmbox custom">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ullamcorper eleifend augue, at eleifend lacus tincidunt sed. Nam et ipsum non dui pellentesque suscipit at finibus metus. Nullam vel augue eros. Sed sodales mi ut sodales posuere. Nullam eleifend nisl vel urna bibendum egestas. Sed eget dolor nunc. Curabitur elementum dolor sit amet enim pellentesque, vitae cursus tellus tempus. Maecenas non cursus nisl, sit amet volutpat nisl. Integer faucibus at nunc eget euismod.
</div>
</span>
<span style="position: relative">[hover me3]
<div class="jsmbox custom">This text is much shorter!</div>
</span>
The first div (hover me1) is fully auto dimensioned and the text doesn't even fit. [not true! It has max dimensions when it is being hovered over.]
- The second div (hover me2) has fixed width.
- Third div (hover me3) also has fixed width, but the text is shorter and so aspect ratio is incorrect and div is too large for its content...