如何实现CSS导航标签(nav-tabs)在任意设备宽度下居中?
解决Flex导航标签的居中问题
嘿,我来帮你搞定这个导航标签居中的问题!你之前尝试的margin: 0 auto和width:100%没生效,是因为flex容器的默认水平对齐方式是flex-start,这个时候用margin auto的方式并不适用——flex布局有自己的居中方法。
下面是针对你现有代码的具体修改方案:
1. 给Flex容器添加居中对齐属性
直接给ul.nav.nav-tabs加上justify-content: center,这是flex布局中让子元素水平居中最直接有效的方式。另外你原来的padding-left:10px会让整个导航偏右,建议改成左右对称的内边距,比如padding: 0 10px,这样既保留了左右的空隙,又不会破坏居中效果。
修改后的容器CSS代码:
ul.nav.nav-tabs{ display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-flow: row nowrap; -ms-flex-flow: row nowrap; flex-flow: row nowrap; /* 新增:让flex子元素水平居中 */ -webkit-justify-content: center; justify-content: center; margin: 0; padding: 0 10px; /* 替换原padding-left,保持左右对称 */ }
2. 修正一个小错误
你在li的样式里写了white-space: wrap,这是无效的属性值哦!正确的选项是nowrap(让标签文字不换行)或者normal(默认自动换行)。考虑到导航标签的设计,建议改成white-space: nowrap,避免文字换行导致标签高度变化:
ul.nav.nav-tabs li{ list-style: none; margin: 0; padding: 0; position: relative; white-space: nowrap; /* 修正无效属性值 */ }
3. 可选:适配小屏幕换行
如果希望在手机等极小屏幕上,导航标签能自动换行而不出现横向滚动条,可以把flex-flow: row nowrap改成flex-flow: row wrap,这样当容器宽度不够时,标签会自动换行,而且每一行都会保持居中:
ul.nav.nav-tabs{ /* ...其他属性不变 */ -webkit-flex-flow: row wrap; -ms-flex-flow: row wrap; flex-flow: row wrap; }
完整修改后的CSS参考
ul.nav.nav-tabs{ display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-flex-flow: row nowrap; -ms-flex-flow: row nowrap; flex-flow: row nowrap; -webkit-justify-content: center; justify-content: center; margin: 0; padding: 0 10px; } ul.nav.nav-tabs li{ list-style: none; margin: 0; padding: 0; position: relative; white-space: nowrap; } ul.nav.nav-tabs li:last-child:after{ content: ""; background: url(""); } ul.nav.nav-tabs li.active:after { background: url(../images/right-chevron-orange.png) center right -3px no-repeat; background-size: 16px; } ul.nav.nav-tabs li:after{ content: ""; background: url(../images/right-chevron.png) center right -3px no-repeat; width: 20px; background-size: 16px; position: absolute; height: 20px; right: 6px; top: 18px; } .nav-tabs>li{ width: auto; height: auto; margin-bottom: 5px; }
这样修改之后,不管是在电脑、平板还是手机上,你的导航标签都会始终保持水平居中啦!
内容的提问来源于stack exchange,提问作者Pooja Krishna
相关产品推荐
相关产品推荐

