试图将导航置于页面中心并占据输入宽度。我发现有几个页面建议添加 display inline-block 但这不起作用。我也试过将导航的宽度设置为 100%,但这也不起作用。我还尝试将 margin-right 和 margin-left 设置为自动。谢谢。
代码笔:https://codepen.io/centem/pen/BaajLZm
CSS
body {
margin: 0 auto;
}
a {
text-decoration: none;
}
nav {
font-family: monospace;
width: 100%;
margin: auto;
}
ul {
background: rgb(67, 66, 66);
list-style: none;
margin: 0;
padding-left: 0;
}
li {
color: #fff;
background: rgb(67, 66, 66);
display: block;
float: left;
padding: 1rem;
position: relative;
text-decoration: none;
transition-duration: 0.3s;
}
li a {
color: #fff;
}
li:hover,
li:focus-within {
background: rgb(0,0,0);
cursor: pointer;
}
li:focus-within a {
outline: none;
}
ul li ul {
background: rgb(67, 66, 66);
visibility: hidden;
opacity: 0;
min-width: 5rem;
position: absolute;
transition: all 0.3s ease;
margin-top: 1rem;
left: 0;
display: none;
}
ul li:hover > ul,
ul li:focus-within > ul,
ul li ul:hover,
ul li ul:focus {
visibility: visible;
opacity: 1;
display: block
}
ul li ul li {
clear: both;
width: 100%;
}
最佳答案
您可以使用 flex
让您对中心感到满意。此外,需要清除 float 内容才能到达下一行。下面是重构后的代码。
body {
margin: 0 auto;
}
a {
text-decoration: none;
}
nav {
font-family: monospace;
width: 100%;
margin: auto;
display: block;
display: flex;
justify-content: center;
}
nav::after {
content: "";
display: block;
clear: both;
}
ul {
background: rgb(67, 66, 66);
list-style: none;
margin: 0;
padding-left: 0;
}
li {
color: #fff;
background: rgb(67, 66, 66);
display: block;
float: left;
padding: 1rem;
position: relative;
text-decoration: none;
transition-duration: 0.3s;
}
li a {
color: #fff;
}
li:hover,
li:focus-within {
background: rgb(0, 0, 0);
cursor: pointer;
}
li:focus-within a {
outline: none;
}
ul li ul {
background: rgb(67, 66, 66);
visibility: hidden;
opacity: 0;
min-width: 5rem;
position: absolute;
transition: all 0.3s ease;
margin-top: 1rem;
left: 0;
display: none;
}
ul li:hover>ul,
ul li:focus-within>ul,
ul li ul:hover,
ul li ul:focus {
visibility: visible;
opacity: 1;
display: block
}
ul li ul li {
clear: both;
width: 100%;
}
section {
display: block;
}
<nav>
<ul>
<li><a href="#">One</a></li>
<li><a href="#">Two</a>
<ul>
<li href="#">One</li>
<li href="#">Two</li>
</ul>
</li>
<li><a href="#">Three</a>
<ul>
<li href="#">One</li>
<li href="#">Two</li>
<li href="#">Three</li>
</ul>
</li>
<li><a href="#">Four</a></li>
<li><a href="#">Five</a></li>
</ul>
</nav>
<section>
<div class="section-header">
<span>One</span>
<span>Two</span>
<span>Three</span>
</div>
<div class="content">CONTENT</div>
</section>
<footer>
</footer>
关于html - 页面的中心导航和跨度宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58352759/