CSS设置section尺寸后需内容才显示?新手技术求助
块级元素仅设宽高却不显示的问题解决
问题说明
我是前端新手,排查资料后仍未解决问题:设置了width、height等CSS属性的section或div元素,必须添加内容(哪怕是随机短文本)才会在浏览器中显示;但观察到其他开发者无需在块级元素内添加内容,仅通过设置宽高属性就能让元素正常显示。附上两张对比图:他人实现效果、我的显示效果。目前未找到同类问题的相关信息,检查代码后也未发现异常,现将代码附上,请求帮助解决。
我的代码
CSS 代码
*{ margin: 0; /*universal setting for no body margins*/ padding: 0; } header{ width: 100%; /*Occupy the entire width of the page*/ height: 50px; background-color: whitesmoke; } main{ width: 100%; height: 90%; background-color: rgb(185, 255, 92); display: flex; justify-content: space-between; } section{ width: 40%; height: 100%; background-color: rgb(125, 184, 251); } .sect1{ width: 70%; } .sect2{ width: 25%; } footer{ width: 100%; height: 50px; background-color: rgb(255, 0, 0); }
HTML 代码
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="reset.css"> <link rel="stylesheet" href="style.css"> <title>Challenge Alura ONE #1 - Encriptador</title> </head> <body> <header> <img src="imgs/LogoOGLog.svg" alt="Small Allura's logo"> </header> <main> <section class="sect1"> dasdfaf </section> <section class="sect2"> fgasfgasf </section> </main> <footer> </footer> </body> </html>
问题原因与解决方案
核心原因
main元素设置了height: 90%,但它的父元素html和body没有设置高度,导致百分比高度没有参照基准,main的实际高度无法被正确计算。当内部section没有内容时,就没有足够的高度来撑显背景色和宽高。
解决方法
- 给
html和body设置100%高度,为main的百分比高度提供参照:
html, body { height: 100%; }
- 调整
main的高度,避免与header、footer的高度冲突(两者总高度为100px):
main{ width: 100%; height: calc(100% - 100px); /* 减去header和footer的总高度 */ background-color: rgb(185, 255, 92); display: flex; justify-content: space-between; }
修改后,即使section内没有内容,也会因为main有了正确的高度,自身的height:100%能生效,从而正常显示出设置的宽高和背景色。
补充方案
如果不想依赖父元素的百分比高度,也可以直接给section设置固定高度(如height: 600px),这样无需依赖父元素高度也能直接显示。
内容的提问来源于stack exchange,提问作者Retablo Autómata
相关产品推荐
相关产品推荐

