动态调整元素大小,但保持其背景的比例

时间:2015-06-14 16:36:22

标签: jquery css

我有一个容器,每行有4个元素。它们会按比例动态改变大小,但是它们有一个多精灵背景图像(在此演示中不会旋转)。

enter image description here

我将容器的宽度设置为 23.75%,我将什么设置为我的高度,以便我的背景图像的(小部分)始终成比例?

.body {
    margin: 15px;
    background: grey;
}
.container {
    background-image: url("http://i.imgur.com/MUQ1HxQ.jpg"); 
    background-size: 600% 100%;
    background-position: 0px 0px;
    margin-right: 1%;
    width: 23.75%;
    height: 15vw;
    display: inline-block;
}
.body .container:nth-child(4n+1) {
    margin-left: 1%;
} 

JsFiddle

1 个答案:

答案 0 :(得分:0)

Here's the solution I came up with(css + Jquery)

.body {
    margin: 15px;
    background: grey;
}
.container {
    background-image: url("http://i.imgur.com/MUQ1HxQ.jpg"); 
    background-size: 600% 100%;
    background-position: 0px 0px;
    margin-right: 1%;
    width: 23.75%;
    height: 15vw;
    display: inline-block;
}
.body .container:nth-child(4n+1) {
    margin-left: 1%;
} 
<div class="body">

<div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div><div class="container"></div>

</div>
$(window).ready(updateHeight);
$(window).resize(updateHeight);

function updateHeight()
{
    var div = $('.container');
    var width = div.width() * 0.56;

    div.css('height', width);
}