var $parent = $('.parent'),
$child = $('.child'),
w = $parent.width(),
h = $parent.height(),
cw = $child.width(),
ch = $child.height(),
winc = -10,
hinc = -5;
/*
This function is what you need.{
First we grab the ratio for the width (rx).
Then the ratio for the height (ry).
To scale to FIT, we want the MIN of the two.
To scale to FILL, we want the MAX of the two.
r is used to calculate the new size for ther child obj.
*/
function calcChildSize() {
var rx = w/cw,
ry = h/ch,
r1 = Math.min(rx, ry),
r2 = Math.max(rx, ry);
$('.child.fit').css({
width: r1 * cw,
height: r1 * ch
});
$('.child.fill').css({
width: r2 * cw,
height: r2 * ch
});
}
// just a simple function to change the size
// of the parent object
window.setInterval(function() {
if (w < 70) {
winc = 10;
} else if (w > 200) {
winc = -10;
}
if (h < 50) {
hinc = 5;
} else if (h > 200) {
hinc = -5;
}
w += winc;
h += hinc;
$parent.css({
width: w,
height: h
});
calcChildSize();
}, 100);
.parent {
display: inline-block;
width: 200px;
height: 200px;
border: 1px solid #aaa;
margin-right: 50px;
}
.child {
box-sizing: border-box;
width: 50px;
height: 70px;
background: rgba(0, 0, 0, 0.2);
border: 1px solid rgba(255, 0, 0, 0.5);
text-align: center;
font-family: monospace;
font-size: 11px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent fit">
<div class="child fit">FIT</div>
</div>
<div class="parent fill">
<div class="child fill">FILL</div>
</div>
** max-height:100%**を.boxに設定すると、効果が得られますか? – KujAslani
私はそれを試みましたが効果はありません。 – Soumith
私の答えをチェックし、私に知らせてください。 – KujAslani