我有一个div在另一个div里面,它的背景是一个电话。我正试图使内部div随着视窗变小而调整大小。
您可以看到演示here
HTML格式
<div class="phone-container">
<div class="screen">
</div>
</div>
CSS
.phone-container {
position: relative;
background: url(http://imgur.com/eyIzwSW.jpg) no-repeat;
background-size: contain;
width: 25.188em;
height: 50em;
max-width: 90%;
}
.screen {
position: absolute;
left: 8.1%;
top: 15.1%;
width: 82.5%;
height: 65.1%;
background-color: green;
overflow: hidden;
}
当视窗为正常大小时,效果很好,如果要逐渐减小视窗的大小,则内部div的宽度会适当调整,但高度保持不变。关于如何在不使用JavaScript的情况下使内部div的高度正确响应,有什么建议吗?
最佳答案
百分比top
基于元素父元素的height
。在您的例子中,当您调整窗口大小时,父窗口的height
不会更改,因此子窗口的top
也不会更改。请参见documentation for top
。
我成功地使用了不同的结构,让图像定义.phone-container
的高度:
<div class="phone-container">
<img src="http://imgur.com/eyIzwSW.jpg" />
<div class="screen"></div>
</div>
.phone-container {
position: relative;
width: 90%;
max-width:552px;
}
.phone-container img {
position:relative;
width:100%;
}
.screen {
position: absolute;
left: 8.1%;
top: 15.1%;
width: 82.5%;
height: 65.1%;
background-color: green;
}
屏幕相对于图像的位置不是像素完美的,但是您可能可以调整这些值以获得更精确的结果。
Working Example (jsFiddle)
关于html - 视口(viewport)变小时,内部div的高度不会调整,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21197694/