嵌套Flex容器中flex-direction: column不生效问题求助
问题:Flex布局下mission-container无法显示在header下方
我尝试创建两个Flex区块:顶部为header导航栏,下方的mission-container位于导航栏下边框之后,二者均嵌套在class为container的div中。我为container类设置了display:flex;和flex-direction:column;,但发现即便父容器设置了纵向排列,mission-container的内容仍无法处于header导航栏的下边框下方。
原始HTML代码
<!DOCTYPE html> <html> <head> <title>The Tea Cozy</title> <link rel="stylesheet" href="style.css" type="text/css" /> </head> <body> <div class="container"> <header> <img src="https://content.codecademy.com/courses/freelance-1/unit-4/img-tea-cozy-logo.png"/> <nav> <ul class="navlinks"> <li>Mission</li> <li>Featured Tea</li> <li>Locations</li> </ul> </nav> </header> <div class="mission-container"> <h1>Hi</h1> <h1>Hi</h1> <h1>Hi</h1> <h1>Hi</h1> </div> </div> </body> </html>
原始CSS代码
body{ background-color:black; } .container{ flex-direction:column; } header{ display:flex; height:69px; width:100%; border-bottom: 1px solid seashell; position:fixed; align-items:center; justify-content:space-between; } header img{ height:50px; margin-left:10px; } .navlinks{ display:inline-flex; color:grey; width:100%; justify-content:flex-end; list-style:none; } li{ margin-right:60px; text-decoration:underline; font-size:20px; } .mission-container{ display:flex; color:white; align-content:center; }
问题原因
container类缺失display:flex属性,导致纵向布局规则未生效;header使用position:fixed后会脱离正常文档流,不再占用父容器空间,使得mission-container直接顶到页面顶部被遮挡;header未设置背景色,下方内容会透过导航栏显示,加重遮挡的视觉效果。
修复方案
修改CSS代码,补上缺失属性并添加边距避开固定元素:
body{ background-color:black; } .container{ display:flex; /* 启用Flex布局 */ flex-direction:column; } header{ display:flex; height:69px; width:100%; border-bottom: 1px solid seashell; position:fixed; align-items:center; justify-content:space-between; background-color:black; /* 添加背景色防止内容穿透 */ } header img{ height:50px; margin-left:10px; } .navlinks{ display:inline-flex; color:grey; width:100%; justify-content:flex-end; list-style:none; } li{ margin-right:60px; text-decoration:underline; font-size:20px; } .mission-container{ display:flex; color:white; align-content:center; margin-top:69px; /* 添加与header高度一致的上边距,避开固定导航栏 */ }
内容的提问来源于stack exchange,提问作者jarvic1207
相关产品推荐
相关产品推荐

