使用bootstrap的navbar-element我需要在导航栏的中心放置一条欢迎信息。我在bootstrap示例中使用了以下HTML结构:
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-5">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-5">
<p class="navbar-text navbar-right welcome-message">Welcome, Tom Delonge</p>
</div>
</div>
</nav>
欢迎&#39;之后的名字动态变化所以我添加了一些jQuery代码让它始终居中:
$(document).ready(function(){
var welcomeMessage = $('.welcome-message');
var width = welcomeMessage.width();
var offset = width / 2;
welcomeMessage.css('margin-right', '-' + offset + 'px');
});
我想知道是否有更好的解决方案仅使用CSS。提前谢谢。
答案 0 :(得分:1)
<强> CSS 强>
.welcome-message {
position: absolute;
left: 50%;
transform:translate(-50%,0);
}
只需上面的CSS就可以了解
答案 1 :(得分:1)
为Welcome text
重构您的课程,并添加一些自定义CSS代码以进行居中。不需要额外的JS。
<强> HTML 强>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-5">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<div class="navbar-collapse" id="bs-example-navbar-collapse-5">
<p class="navbar-text navbar-center welcome-message">Welcome, A very long name here</a></p>
</div>
</div>
</nav>
<强> CSS 强>
.navbar-collapse {
text-align:center;
}
.navbar-center {
display:inline-block;
float:none;
}
答案 2 :(得分:1)
添加此css
@media only screen and (max-width: 770px) {
.welcome-message {
margin-top: -35px;
position: absolute;
left: 50%;
transform:translate(-50%,0);
}
}
@media only screen and (min-width: 770px) {
.welcome-message {
position: absolute;
left: 50%;
transform:translate(-50%,0);
}
}
<强> DEMO 强>
答案 3 :(得分:1)
删除你的javascript并用这个替换css:
.welcome-message {
float: none !important;
text-align: center;
}