我如何*真的*调整HTML + CSS中的水平菜单? [英] How do I *really* justify a horizontal menu in HTML+CSS?
问题描述
您在HTML中的菜单栏上找到了很多教程,但是对于这个特定的(虽然IMHO泛型),我没有找到任何正确的解决方案:
#菜单项目应该是正确的,因为普通文本应该是#
#^ ^#
- 有不同数量的纯文本菜单项,页面布局是流畅的。
- 第一个菜单项应该
- 剩余的项目应该在菜单栏上最佳地展开。
- 因此没有机会预先计算最佳宽度。
请注意,TABLE不会在这里工作:
- 如果您集中所有TD,则第一个和最后一个项目未正确对齐。
- 如果您左对齐并右对齐第一个或第二个。
很奇怪,没有明显的方法来实现这一点。使用HTML和CSS清除方式?
现代方法 - Flexboxes !
现在 CSS3 flexboxes 有更好的浏览器支持,我们中的一些人最终可以开始使用它们。只需添加更多浏览器覆盖率的其他供应商前缀即可。
在此实例,您只需将父元素的 display
设置为 flex
,然后更改 justify-content
属性以 之间的空格
或 space-around
,以便在儿童flexbox项目之间或周围添加空间。
使用 justify-content:space-between
- ( ) : :
ul {list-style:none; padding:0; margin:0;}。 justify-content:space-between;}
< ul class =menu> < li>第一项< / li> < li>第二项< / li> < li>第三项较长< / li> < li>第四项< / li>< / ul>
< hr>
使用 justify-content:space-around
- (example here) :
ul {list- style:none; padding:0; margin:0;}。menu {display:flex; justify-content:space-around;}
< ul class =menu> < li>第一项< / li> < li>第二项< / li> < li>第三项较长< / li> < li>第四项< / li>< / ul>
You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:
# THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
- There's an varying number of text-only menu items and the page layout is fluid.
- The first menu item should be left-aligned, the last menu item should be right-aligned.
- The remaining items should be spread optimally on the menu bar.
- The number is varying,so there's no chance to pre-calculate the optimal widths.
Note that a TABLE won't work here as well:
- If you center all TDs, the first and the last item aren’t aligned correctly.
- If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.
Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS?
Modern Approach - Flexboxes!
Now that CSS3 flexboxes have better browser support, some of us can finally start using them. Just add additional vendor prefixes for more browser coverage.
In this instance, you would just set the parent element's display
to flex
and then change the justify-content
property to either space-between
or space-around
in order to add space between or around the children flexbox items.
Using justify-content: space-between
- (example here):
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-between;
}
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
Using justify-content: space-around
- (example here):
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-around;
}
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
这篇关于我如何*真的*调整HTML + CSS中的水平菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!