[英]Navbar with Title in center and buttons to right
所以我試圖創建一個導航欄,標題在中心,按鈕出現在右側。 如您所見,當我嘗試執行此操作時,按鈕出現在下一行和 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; }
<div class="title-bar"> <div class="title">Title</div> <div class="button"> <button class="buts">Whats Up</button> </div> </div>
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; }
<div class="title-bar"> <div class="title">Title</div> <div class="button"> <button class="buts">Whats Up</button> </div> </div>
編輯:在@burak 的評論之后,它並不完全位於中心。
正如您在下圖中所看到的,有些空間是由Whats Up按鈕獲取的,這就是為什么標題不在正中央,而文本在其父項的正中央。
我們也可以將它設置在精確的中心,但為此我們需要使用position:absolute
將Whats Up按鈕移動到另一層
.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; }
<div class="title-bar"> <div class="title">Title</div> <div class="button"> <button class="buts">Whats Up</button> </div> </div>
我為標題欄使用了 flexbox,並讓左側所需的邊距自動計算。
.title-bar { display: flex; justify-content: center; width: 100%; } .title, .button { margin-left: auto; }
<div class="title-bar"> <div class="title">Title</div> <div class="button"> <button class="buts">Whats Up</button> </div> </div>
使用 display:inline; 這樣標題和按鈕都會出現在同一行。
.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; } .buttonRight{ position:absolute; right:0; top:0; padding:5px; }
<div class="title-bar"> <div class="title">Title</div> <div class="buttonRight"> <button class="btn btn-primary">Whats Up</button> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.