如果我将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;
}
有人能帮我吗?
我在不同的网站上搜索,似乎没有什么对我有用。
最佳答案
这是因为默认值是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。那么,如果
建立静态位置的元素的“direction”属性
包含块是'ltr'将'left'设置为静态位置
“width”和“right”是“auto”,而“left”不是“auto”,则
宽度缩小到合适的尺寸。
您可以尝试设置另一个宽度,例如
width: 100%
。但请注意,百分比将根据containing block来解析,对于固定元素,它通常是视区。考虑将
position: relative
添加到父元素,并在元素中使用position: absolute
而不是fixed
,以便width: 100%
使其与父元素一样宽。关于html - 使用位置:固定时,为什么导航的宽度与CSS中的容器宽度相同?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40709518/