如何在header元素内将导航菜单置于背景图片下方?
解决方案
要把导航菜单放在header背景图的下方,只需调整header的布局方式,让内部元素垂直分布并将导航固定在底部。修改后的代码如下:
目标效果

修改后的代码
CSS
header { background-image: url(https://picsum.photos/1536/1354); height: 250px; background-repeat: no-repeat; background-position: center; margin: 1em; padding: 1em; grid-area: header; /* 添加flex布局,垂直排列内部元素 */ display: flex; flex-direction: column; justify-content: space-between; } nav ul { margin: 0px; padding: 0px; list-style-type: none; display: flex; justify-content: center; } nav ul li a { display: block; border: 1px solid; border-radius: .5em; padding: .25em; margin: .5em; }
HTML
<header id="banner"> <h1>Dentistry Page</h1> <nav> <ul> <li><a href="index.html">Home</a></li> <li><a href="Services/services.html">Services</a></li> <li><a href="About/about.html">About</a></li> <li><a href="Contact/contact.html">Contact</a></li> </ul> </nav> </header>
关键改动说明
- 给
header添加display: flex和flex-direction: column,让内部元素垂直排列 - 用
justify-content: space-between把标题和导航分别推到header的顶部和底部,确保导航固定在背景图的下方区域 - 移除
nav ul中的align-items: flex-end,因为整体位置已通过header的布局控制
内容的提问来源于stack exchange,提问作者foofghtr7
相关产品推荐
相关产品推荐

