如何为初始无内容div设置背景 实现页面分区差异化背景效果
问题原因
你现在遇到的背景显示异常和Eric Meyer的重置样式无关,核心是两个布局逻辑问题:
- 你把古董白背景设置在了外层
#wrapper上,这个容器占满了整个视口高度,内部空的#bottomPartOfPage因为没有内容,默认高度为0,自然透不出你设置的白色背景,看起来就是整个页面都是单一的古董白 - 百分比高度的继承链断裂:你只给
body设置了height:100vh,没有给html标签设置高度基准,同时#wrapper用min-height:100%的时候,没有做布局适配让底部区域自动填充剩余空间。另外你的HTML里还有个笔误:<secion>标签少打了个t,正确写法是<section>,这个笔误不影响背景显示,但会导致语义化异常。
修复步骤
- 把原来挂在
#wrapper上的古董白背景,移到顶部容器#topPartOfPage上,只给头部区域用这个背景色 - 给
html、body都设置height:100%,补全高度继承链,把原来写在body上的max-width:1680px移到#wrapper上,符合布局逻辑 - 给
#wrapper设置纵向flex布局,给#bottomPartOfPage加flex:1属性,让它不管有没有内容,都自动撑满头部以下的剩余空间,正常显示白色背景 - 修正HTML里的标签拼写错误,补全
id="buttons"的属性引号。
修正后完整代码
CSS部分(重置样式保留不变,只修改自定义样式段)
/* 重置样式保持你原来的Eric Meyer Reset 2代码不变,只修改下方自定义样式 */ /* Beginning of CSS for the Page that is not Eric Meyer's Reset Code */ html, body { height: 100%; margin: 0; } body { background: rgb(211,211,211); } #wrapper { width: 90%; max-width: 1680px; margin: 0 auto; min-height: 100%; display: flex; flex-direction: column; } header > h1 { font-size: 2rem; font-weight: bold; padding: 1rem 0; margin-left: 10px; } #topPartOfPage { display: flex; flex-flow: row nowrap; justify-content: space-around; align-items: center; height: 275px; width: 100%; background: antiquewhite; } #bottomPartOfPage { display: flex; flex-flow: row wrap; justify-content: space-evenly; width: 100%; flex: 1; background: white; }
HTML部分
<html lang="en"> <head> <title>Flashcards</title> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css" /> </head> <body> <div id="wrapper"> <div id="topPartOfPage"> <header> <h1>Flashcards</h1> </header> <section>Form Elements for Creating the Flashcards</section> <div id="buttons"> <button type="button">Open up form elements</button> <button type="button">Delete all flashcards</button> </div> </div> <div id="bottomPartOfPage"> </div> </div> </body> </html>
最终效果
- 顶部固定275px高的头部区域(标题、表单、按钮)显示古董白背景
- 头部以下的闪卡放置区,哪怕没有任何内容,也会自动占满剩余视口高度,显示白色背景
- 后续JS动态追加闪卡时,如果内容总高度超过视口剩余高度,闪卡区会自动撑开,白色背景会随内容延伸,不会出现背景断层或颜色错乱。
内容的提问来源于stack exchange,提问作者William S
相关产品推荐
相关产品推荐

