【问题标题】:How to make the navbar stay at the top in CSS [duplicate]如何使导航栏在CSS中保持在顶部[重复]
【发布时间】:2021-08-27 09:16:10
【问题描述】:

我想要一些关于如何让我的导航栏在 CSS 中保持在顶部的帮助。从技术上讲,我使用的是 Sass,但 CSS 与 Sass 兼容,所以一切都很好(只要它有效!)。

我知道这个问题已经被问过好几次了,但通常是用 JavaScript 或者没有回答这个问题。我已经尝试过使用position:sticky,但可能是我放错了标签。

这里是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.0">
        <link rel="stylesheet" href="../../static/css/styles.css">
        <title>Home</title>
    </head>
    <body>
        <div class="navbar">
            <h1>SomeCompany</h1>

            <ul>
                <li><a href="localhost:8000">Home</a></li>
                <li><a href="localhost:8000">About</a></li>
                <li><a href="localhost:8000">Products</a></li>
                <li><a href="localhost:8000">Testimonials</a></li>
                <li><a href="localhost:8000">Contact Us</a></li>
            </ul>
        </div>
    </body>
</html>

现在,这是 CSS 代码(我在 .navbar 中使用 position:sticky):

body {
margin: 0; }

.navbar {
    position: sticky;
    padding: 1em 2em;
    background-color: antiquewhite;

    h1 {
        margin: 0; }

    ul {
        position: relative;
        bottom: 1em;
        float: right;

        li {
            display: inline;
            margin-right: 2em; }
    }
}

提前谢谢你

【问题讨论】:

    标签: html css navbar


    【解决方案1】:

    您可以尝试在 css 中添加 position:absolute;和顶部:0;导航栏类。

    【讨论】:

      【解决方案2】:

      我相信您正在尝试做的事情在这里描述:https://www.w3schools.com/howto/howto_css_fixed_menu.asp

      【讨论】:

        【解决方案3】:

        您需要在导航栏中定义top: 0px;(或任何您想要的值)然后它应该可以工作。

        【讨论】:

        • 感谢 Benchy 的建议!它是 Misfits09 提到的链接的一部分。也感谢您的即时回复。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-01-01
        • 2012-07-24
        • 2016-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-03
        相关资源
        最近更新 更多