我有一个div平方,它由padding-bottom: 100%;
平方并为孩子设置position: absolute;
。当父div的宽度大于高度时,出现方形溢出屏幕和滚动条。有没有办法使平方适合父div?
很抱歉误导您。是的,我想将方形框放入父div。 我为示例创建了新的js小提琴
div.stretchy-wrapper {
width: 100%;
padding-bottom: 100%;
position: relative;
opacity: 0.5;
background: darkgreen;
}
@media all and (orientation: landscape) {
div.stretchy-wrapper {
width: 100vh;
height: 100vh;
padding-bottom: 0;
}
}
div.stretchy-wrapper > div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
color: black;
font-size: 24px;
text-align: center;
}
.outercontainer {
background: red;
width: 400px;
height: 200px;
}
<div class="outercontainer">
<div class="stretchy-wrapper"></div>
</div>
答案 0 :(得分:2)
如果您以width
模式查看视口,请添加一个mediaquery以限制元素的height
和landscape
@media all and (orientation: landscape) {
div.stretchy-wrapper {
width: calc(100vh - 20px);
height: calc(100vh - 20px);
padding-bottom: 0;
}
}
换句话说:如果视口的宽度是≥
的高度,则要确保1:1
的宽高比,可以将width
设置为等于100vh
(减去填充(如果需要),则height
应该等于宽度。同样,在发生这种情况时,padding-bottom
也不再需要。
由于outercontainer
的高度是固定的,因此如果视口宽度为≥ 200px
,则将200px
的宽度和高度都设置为固定值。否则,使用伪指令来保留1:1
的宽高比:
div.stretchy-wrapper::before {
display: block;
content: "";
padding-bottom: 100%;
}
@media all and (min-width: 200px) {
div.stretchy-wrapper {
width: 200px;
height: 200px;
}
div.stretchy-wrapper::before {
display: none;
}
}
.outercontainer {
max-width: 400px;
height: 200px;
border: 1px #9cb dashed;
}
.stretchy-wrapper {
background: #9bc;
}
<div class="outercontainer">
<div class="stretchy-wrapper"></div>
</div>
最终结果
答案 1 :(得分:0)
一种实现此目的的方法是根据视口高度(vh单位,如answer provided by @fcalderan)来设置div的宽度和高度,然后根据的高度来设置max-width和max-height视口:
div.stretchy-wrapper {
position: relative;
background: darkgreen;
width: calc(100vh - 20px);
height: calc(100vh - 20px);
max-width: calc(100vw - 20px);
max-height: calc(100vw - 20px);
}
这样,无论视口如何变化,div都将保持正方形(但不需要mediaquery)。