2015-10-30 67 views
25

我對Flexbox完全陌生並希望對齊按鈕,但我無法看到如何使用中心對齊的按鈕和右側來處理常見情況只使用Flexbox對齊同一行上的按鈕。如何使用Flexbox居中對齊一個Flex項目並右對齊另一個使用Flexbox

但是,我找到了一種方法,使用與右對齊項目相同長度的不可見左對齊項目以及使用space-between的flex justify-content使中間項目居中在該行上。

Flexbox有更直接的方法嗎?

.flexcontainer { 
 
    display: flex; 
 
    justify-content: space-between; 
 
    width: 500px; 
 
    height: 200px; 
 
} 
 
.iteminvisible { 
 
    flex: 0 1 auto; 
 
    width: 100px; 
 
    height: 100px; 
 
    visibility: hidden; 
 
} 
 
.itemcenter { 
 
    flex: 0 1 auto; 
 
    width: 150px; 
 
    height: 100px; 
 
    .itemright { 
 
    flex: 0 1 auto; 
 
    width: 100px; 
 
    height: 100px; 
 
    }
<div class="flexcontainer"> 
 
    <div class="iteminvisible">Other</div> 
 
    <div class="itemcenter">One</div> 
 
    <div class="itemright">Other</div> 
 
</div>

回答

-2

從什麼我瞭解,該按鈕要「浮動」的權利不應該flex: 0 1 auto而是flex: 0 0 autoflex樣式中的第一個參數決定項目是否應該增長。如果你不希望它填滿更多的空間,不要讓它增長。

9

使用justify-content: space-between帶有不可見的flex項目,如問題中所述,是實現所需佈局的好方法。請注意,如果左側和右側的項目長度相同(see demo),則中間項目只能居中。

您可能要考慮的另一個解決方案涉及auto marginsabsolute positioning。這種方法的兩個好處是不需要額外的標記,並且無論項目大小如何都可以實現真正的對中。一個缺點是從document flow中刪除居中的物品(這可能對您沒有關係)。

.flexcontainer { 
 
     display: flex; 
 
     justify-content: flex-start; /* adjustment */ 
 
     position: relative;   /* new */ 
 
     width: 500px; 
 
     height: 200px; 
 
    } 
 

 
.itemcenter { 
 
     flex: 0 1 auto; 
 
     width: 150px; 
 
     height: 100px; 
 
     position: absolute;    /* new */ 
 
     left: 50%; 
 
     transform: translateX(-50%); 
 
    } 
 

 
.itemright { 
 
     flex: 0 1 auto; 
 
     width: 100px; 
 
     height: 100px; 
 
     margin-left: auto;    /* new */ 
 
    }
<div class="flexcontainer"> 
 
    <div class="itemcenter">One</div> 
 
    <div class="itemright">Other</div> 
 
</div>

更多細節在這裏:Methods for Aligning Flex Items along the Main Axis(見盒#62-78)。

6
.container { 
     display: flex; 
     flex-direction: column; //this will allow flex-end to move item to the right    
     align-items: center; 
    } 
    .right-item { 
     align-self: flex-end; 
    } 
+0

但是,這將正確的項目放在中間的一個下面,不是嗎? – jordan314