![](/img/trans.png)
[英]How can I horizontally center two columns of list items(with or without Bootstrap)?
[英]How to center content horizontally without overlapping items on the side
我正在嘗試創建一個類似於iOS的UINavigationBar的視圖布局:
UINavigationBar的標題以屏幕為中心,兩側都有可選的導航項(按鈕)。 如果標題太寬而不適合中心,那么它將被推到一邊以避免重疊導航項。
沒有 JavaScript,這樣的布局是否可以在CSS中使用?
這是我創建的一個小提琴 ,試圖實現這種布局。
在上面的屏幕截圖中,通過浮動兩側的紅色和藍色按鈕,並將黃色div的左右邊距設置為auto
來實現布局。 上面的第二行正是我想要的,但不幸的是我必須在黃色div上設置一個顯式寬度。
我也嘗試過flexbox,但它不允許我將黃色div放在容器中心。
如果在這種情況下無法避免使用JavaScript,那么實現它的最佳方式(與每個瀏覽器最兼容)是什么?
使用絕對定位放置左/右列。
.left,
.right {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.center {
padding: 0 200px; // Add indents so columns don't overlap its content.
}
.row { border: 1px solid black; position: relative; margin: 20px 0; padding: 5px 0; } .left, .right { position: absolute; } .left { background-color: red; width: 200px; left: 0; } .right { background-color: cyan; right: 0; } .center { margin: 0 auto; background-color: yellow; text-align: center; white-space: nowrap; padding: 0 200px; } .fixed { width: 130px; } .zero { width: 0px; }
<div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div>
您可以使用position: absolute
來精確地row
的中間實現center
div,而不管左右的位置。
此外,提供position: relative
對於left
和right
具有更高的z-index
,以使它們出現在center
上方。
參考代碼:
.row { border: 1px solid black; margin: 20px 0; padding: 5px 0; position: relative; height: 18px; } .left { float: left; background-color: red; width: 200px; position: relative; z-index: 2; } .right { float: right; background-color: cyan; position: relative; z-index: 2; } .center { margin: 0 auto; background-color: yellow; text-align: center; white-space: nowrap; } .absolute { position: absolute; left: 0; right: 0; } .zero { width: 0px; } @media only screen and (max-width: 565px) { .absolute { left: 200px; padding-left: 20px; text-align: left; } }
<div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center absolute">center center center</div> </div> <div class="row"> <div class="left">left</div> <div class="right">right</div> <div class="center zero">center center center</div> </div>
將浮動更改為絕對定位,將“行”作為其“錨點”
.row{
position: relative
}
.left,
.right {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
你可以將這些屬性賦予黃色div:
position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.