如何在CSS中将UL内导航栏链接垂直居中并实现LI元素垂直居中?
导航栏垂直居中与链接样式设置方案
1. UL内导航链接垂直居中 + LI在UL内垂直居中(UL已在DIV中居中)
要实现多层垂直居中,用Flex布局逐层处理最省心:
- 外层DIV(
#nav_link)已有水平居中的justify-content: center,加个align-items: center就能让UL在DIV里垂直居中。 - 先重置UL的默认样式:去掉自带的
margin、padding和项目符号,再给UL设display: flex; flex-direction: column; justify-content: center; height: 100%;,这样LI元素就能在UL内部垂直居中分布。 - LI标签设
display: flex; align-items: center;,确保里面的A标签在LI里也能垂直居中(如果LI有固定高度的话效果更明显)。
2. 设置LI内A标签的样式
直接通过#nav_link li a选择器定义链接的各种状态样式即可,比如去掉下划线、调整颜色、加交互效果:
完整代码示例
CSS
/* 重置UL默认样式 */ #nav_link ul { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; justify-content: center; height: 100%; gap: 1.5rem; /* 控制LI之间的间距 */ } #nav_link { background: orange; display: flex; justify-content: center; align-items: center; /* 让UL在DIV中垂直居中 */ outline: 2px solid white; margin-top: 30px; width: 12%; height: 15rem; } #nav_link li { display: flex; align-items: center; justify-content: center; text-align: center; font-size: 20px; } /* 自定义A标签样式 */ #nav_link li a { text-decoration: none; /* 移除默认下划线 */ color: #fff; /* 设置文字颜色 */ padding: 0.5rem 1rem; /* 扩大点击区域 */ } #nav_link li a:hover { background-color: rgba(255,255,255,0.2); /* hover时的背景高亮 */ border-radius: 4px; } #nav_link li a:active { color: #ddd; /* 点击时的文字变化 */ }
HTML
<nav> <div id="nav_link"> <ul> <li><a href="home.html">Home</a></li> <li><a href="">About</a></li> <li><a href="">Contact Us</a></li> <li><a href="">Services</a></li> <li><a href="">Pricing</a></li> </ul> </div> </nav>
关键说明
- UL设置
height: 100%是为了继承外层DIV的高度,配合justify-content: center实现LI的垂直居中。 gap属性用来控制LI之间的间距,比用margin更简洁易维护。- A标签添加内边距不仅能美化样式,还能增大点击区域,提升用户体验。
内容的提问来源于stack exchange,提问作者Nicer Web
相关产品推荐
相关产品推荐

