html - 将 UL 列表拉伸(stretch)为水平导航栏,间距均匀...外边距也有空格

标签 html css html-lists navigationbar

感谢this tip,我花了大半个晚上试图获得一个水平导航栏并设法将其设置并居中。 .然而,这段代码给出了均匀分布的元素并紧靠页面边缘(或区域、div,或它们在里面的任何东西)。

我想要的是它们在它们内部的内容之间均匀分布,并且相同大小的空间出现在外边距上,即在第一个元素之前和最后一个元素之后。

作为引用,这是我的 HTML:

<ul id = "nav">
    <li>Accueil</li>
    <li>Recherche</li>
    <li>Contact</li>
</ul>

这是我的 CSS:

#nav {
    width: 100%;
    text-align: justify;
    margin: 0 0 3em 0;
    padding: 8px;
    list-style: none;
    border-bottom: 1px solid #ccc; 
    border-top: 1px solid #ccc;
}

#nav:after {
    content: '';
    display: inline-block;
    width: 100%;
}

#nav li {
    width: 15%;
    display: inline-block;
    padding: 4px 15px;
    text-align: center;
    text-decoration: none;
    background-color: #f2f2f2;
    border: 1px solid #ccc;
    border-radius: 
}

有没有办法在不指定固定边距或人为“挤压”区域内容的情况下做到这一点?任何帮助将不胜感激。非常感谢!

更新

实际上我的最大宽度限制为 800 像素。所以没有办法流畅地做到这一点?我尝试使用 JavaScript 来计算左边和右边的空格应该是多少,但是如果我超过 5%,这些点就会开始溢出到下一行。

我想我可能遗漏了一些关于列表水平化时“之前”和“之后”方面的确切行为方式的信息。在这一点上,使用一组 div 是否比使用要点更好? (如果列表变得动态,使页面不太合适,但对于一个简单的元素,我怀疑这将是一个问题。)

再次感谢!

更新 BIS

找到了一个很好的解决方案。在这里:

#nav {
    display: flex;
    justify-content: space-around;
    text-align: justify;
    width: 100%;
    margin: 0;
    padding: 8px 0px;
    list-style: none;
    border-bottom: 1px solid #ccc; 
    border-top: 1px solid #ccc;
}

.navItem {
    position:relative;
    width: 15%;
    display: inline-block;
    padding: 4px 15px;
    text-align: center;
    text-decoration: none;
    border: 1px solid #ccc;
    border-radius: 3px;
}
.navSpan { 
    position:absolute; 
    width:100%;
    height:100%;
    top:0;
    left: 0;
    display: block;
}

最佳答案

试试这段代码

#nav {
width: 100%;
text-align: justify;
margin: 0 0 3em 0;
padding: 8px;
list-style: none;
border-bottom: 1px solid #ccc; 
border-top: 1px solid #ccc;
}

#nav:after {
content: '';
display: inline-block;
width: 100%;
}

#nav li {
width: 10%;
display: inline-block;
padding: 4px 2%;
text-align: center;
text-decoration: none;
background-color: #f2f2f2;
border: 1px solid #ccc;
margin-right:12%;
}
#nav:before  {
width: 15%;
display: inline-block;
padding: 4px 15px;
text-align: center;
text-decoration: none;
content:''
}

您需要在窄屏幕(小于 780 像素)上降低 margin-right,因为 % 数字在某些时候变得不准确,但它应该足以让您开始。参见 fiddle here

关于html - 将 UL 列表拉伸(stretch)为水平导航栏,间距均匀...外边距也有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25354397/

相关文章:

css - 如何从CSS中的webelement中找到后代Child

html - 如何在没有此 "hack"的情况下在全屏上制作水平 strip

html - 当我添加 overflow-y 时,我的无序列表消失了

html - 第 n 个子 ul 列表项背景重复到子 ul 列表

css - 如何创建一个填满整个屏幕的垂直 div?

html-lists - CSS UL/LI 菜单不居中

html - IE 中奇怪的 z-index 或链接问题

html - VScode : how-to change the color of HTML open and closing tag

javascript - 如何将一个数组的元素包含在另一个数组中?

html - 在 IIS 6.1 中部署时的页脚 CSS 问题