idu*_*ude 2 html css navbar display
所以我试图创建一个导航栏,中间有一个标题,一个按钮出现在右侧。如您所见,当我尝试执行此操作时,按钮出现在下一行和 div 之外:
.title-bar {
background-color: #48A6B8;
font-style: italic;
margin-bottom: 3%;
color: #fff;
}
.title {
text-align: center;
font-size: 36px;
line-height: 180%;
}
.buts {
float: right;
}Run Code Online (Sandbox Code Playgroud)
<div class="title-bar">
<div class="title">Title</div>
<div class="button">
<button class="buts">Whats Up</button>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
display:inline-block 似乎删除了文本的居中,所以我不能使用它......
提前致谢!
用 flexbox
flex: 1 0 auto;将变得title灵活,它将获得flex-container 中的所有可用空间。
.title-bar {
background-color: #48A6B8;
font-style: italic;
margin-bottom: 3%;
color: #fff;
display: flex;
}
.title {
text-align: center;
font-size: 36px;
line-height: 180%;
flex:1 0 auto;
}Run Code Online (Sandbox Code Playgroud)
<div class="title-bar">
<div class="title">Title</div>
<div class="button">
<button class="buts">Whats Up</button>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
编辑:在@burak 的评论之后,它并不完全位于中心。
正如您在下图中所看到的,Whats Up按钮获取了一些空间,这就是为什么标题不在正中心,而文本在其父项的正中心。
我们也可以将它放在精确的中心,但为此我们需要Whats Up在另一层上移动按钮,通过使用position:absolute
.title-bar {
background-color: #48A6B8;
font-style: italic;
margin-bottom: 3%;
color: #fff;
display: flex;
position:relative;
}
.title {
text-align: center;
font-size: 36px;
line-height: 180%;
flex:1 0 auto;
background:rgba(0,0,0,.5)
}
.button{
position:absolute;
right:0;
top:0;
}Run Code Online (Sandbox Code Playgroud)
<div class="title-bar">
<div class="title">Title</div>
<div class="button">
<button class="buts">Whats Up</button>
</div>
</div>Run Code Online (Sandbox Code Playgroud)