【问题标题】:Why doesn't my nav have the same width as my container in CSS when used position: fixed?为什么我的导航在使用位置时与 CSS 中的容器的宽度不同:固定?
【发布时间】:2016-11-20 21:21:06
【问题描述】:

如果我将position: fixed 添加到nav 的CSS 代码中,导航栏的宽度与容器的宽度不同,有人可以帮我吗?

我的 HTML:

<body>
<div id="container">
    <nav>
        <ul>
            <li><a href="" class="active">Home</a></li>
            <li><a href="guestbook.html">Guestbook</a></li>
            <li><a href="contact.html">Contact</a></li> 
            <li id="login" ><a href="logn.html">Login</a></li> 
        </ul>
    </nav>

<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
<p>Example text</p>
</div>
</body>

我的 CSS:

body {
    background-image: url('img/background.jpg');
    background-repeat: no-repeat;
    background-attachment: fixed;
    margin-top: 0px;
    font-family: Arial;
}

#container {
    background-color:#D3D3D3;
    width: 70%;
    margin: auto;
    overflow:hidden;
}

nav ul {
    list-style-type: none;
    margin: 0;
    overflow: hidden;
    background-color: grey;
}

li {
    float:left;
}

#login {
    float: right;
    padding-right: 40px;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #A1D490;
}

.active {
    background-color: #D3D3D3;
    color: grey;
}

如果我将它添加到 CSS 中,导航栏的宽度就是其内容的宽度:

nav {
    position: fixed;
}

有人可以帮帮我吗? 我在不同的网站上搜索过,似乎没有什么对我有用。

【问题讨论】:

  • nav { position: fixed; left: 0; right: 0; }

标签: html css css-position nav


【解决方案1】:

那是因为默认是width: auto。

对于Block-level, non-replaced elements in normal flow,

以下约束必须保持在其他使用的值之间 属性:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

如果恰好有一个值指定为“auto”,则使用它的值 由等式得出。

如果 'width' 设置为 'auto',任何其他 'auto' 值将变为 '0' 并且 'width' 来自于结果相等。

但是,当您使用 position: fixed 将其取消时,则改为使用 Absolutely positioned, non-replaced elements applies。

如果'left'、'width'和'right'这三个都是'auto':首先设置任意 'margin-left' 和 'margin-right' 的 'auto' 值为 0。然后,如果 建立静态位置的元素的“方向”属性 包含块是 'ltr' 设置 'left' 到静态位置

'width' 和 'right' 是 'auto' 而 'left' 不是 'auto',那么 宽度缩小以适应。

您可以尝试设置其他宽度,例如width: 100%。但请注意,百分比将根据containing block 解析,对于固定元素,通常是视口。

考虑将position: relative 添加到父元素并在元素中使用position: absolute 而不是fixed,以便width: 100% 使其与父元素一样宽。

【讨论】:

  • 谢谢,现在导航的宽度和容器一样。但是我怎样才能固定导航的位置呢?因此,如果我滚动浏览页面,导航会停留在屏幕顶部。
  • 改用position: sticky
  • 谢谢,现在空白空间消失了,这是另一个问题哈哈,但是如果我滚动到底部,我就看不到导航栏,我该如何解决呢? position: fixed 不起作用,它使导航的大小更小(只是内容的宽度)
【解决方案2】:

当它设置为固定时,它会从文档流中取出。它的父母宽度不适用于它。

只需添加 CSS 将导航栏的宽度设置为与容器相同。所以在这种情况下,将其设置为 70%。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多