如果父级没有高度,则子级上的百分比值不起作用,因为当您说height:100%表示父级高度为100%时。
.parent {}
.kid {
width: 100%;
height: 100%;
background-image: url('http://via.placeholder.com/350x150');
}
默认情况下,元素高度是根据其内容的高度计算的。
console.log(document.querySelector('.parent').clientHeight)
.kid {
height: 100px;
width: 100px;
background: orange;
}
在你的情况下,父母有两个孩子
和一个空div,因为你的
中有一些文字,pare not等于它的高度,现在我们知道父母了有一个高度,所以孩子的百分比值应该工作,但事实并非如此,为什么你可能会问?
如果未明确指定包含块的高度(即,它取决于内容高度),并且此元素未绝对定位,则该值将计算为“auto”。根元素的百分比高度相对于初始包含块。
基本上如果我们说:
Parent
height:200px;
Child
height:50% // This should value to 100px;
但是如果我们没有特别设置它会保持自动(意味着取决于内容),那么
Parent
height:auto; which the default value
Child
height:50% // 50% of auto is 0
所以你要么在那个div上设置一个高度。
.parent {
border: 1px solid;
}
.kid {
height: 100px;
background-image: url('http://via.placeholder.com/300x100');
;
background-size: 100% 100%;
}
losadf
或者在父母身上,虽然它可能导致一些溢出。
.parent {
border: 1px solid;
height: 100px
}
.kid {
height: 100%;
background-image: url('http://via.placeholder.com/300x100');
;
background-size: 100% 100%;
}
losadf
或,因为它加载图像并获取它的高度和宽度,我建议你因为你只想显示一个图像,它的高度可以用max-height和max-width完善;
.parent {
border: 1px solid;
}
losadf