如何在Django项目的HTML页面顶部设置导航栏?
解决导航栏显示在页面底部的问题
你的导航栏之所以出现在页面底部,是因为HTML代码里先渲染了<img>元素,导航栏的代码块放在了图片之后。这里提供两种简单的解决方式:
方法1:调整HTML结构(推荐,符合语义化)
直接把导航栏的代码移到<img>标签之前,页面渲染时就会先显示导航栏,再展示图片:
修改后的完整HTML代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Contact Book Template</title> <link type="text/css" rel="stylesheet" href="{%static 'css/style.css' %}" /> <!-- Google Font --> <link href="https://fonts.googleapis.com/css?family=PT+Sans:400" rel="stylesheet"> </head> <body> <!-- 导航栏移至图片前方 --> <div id="booking" class="section"> <div> <ul id="horizantal-style"> <li><a href="#">Home</a></li> <li><a href="#">News</a></li> <li><a href="#">Contact</a></li> <li style="float:right"><a href="#">Login</a></li> <li style="float:right"><a class="active" href="#about">Sign up</a></li> </ul> </div> </div> <img class="contact_book" src="{% static 'img/contact_book.jpg' %}" alt="first" /> </body> </html>
方法2:用CSS固定导航栏到顶部(适合导航栏需始终置顶的场景)
如果希望导航栏固定在页面顶部、不随滚动内容移动,可以给导航栏的ul添加定位样式:
修改你的CSS代码:
ul { list-style-type: none; margin: 0; padding: 0; overflow: hidden; background-color: #dddddd; /* 添加固定定位样式 */ position: fixed; top: 0; width: 100%; } /* 给body添加上边距,避免页面内容被固定导航栏遮挡 */ body { margin-top: 64px; /* 数值匹配导航栏高度,这里a标签上下padding为20px,总高度约64px */ } li { display: inline-block; } li a { display: block; color: #000; text-align: center; padding: 20px 24px; text-decoration: none; } li a:hover { background-color: #555; color: white; } .active { background-color: #337ab7; }
内容的提问来源于stack exchange,提问作者Vivek Mogalla
相关产品推荐
相关产品推荐

