2017-06-22 77 views
1

我正在重建Facebook作爲一個項目來學習一些新概念。其中之一就是使用Flexbox。如何設置兩個彈性項目之間的固定距離?

如果您調整Facebook的登錄頁面大小,您將看到導航變小,但徽標和登錄輸入不會移動,並且空間不會改變。

我看到有人建議我停止使用浮動並使用Flexbox。我已經使用space-between將它們設置爲等同於容器的外邊緣。

問題是,我似乎無法弄清楚當瀏覽器寬度減小時,我如何阻止它們一起移動,就像Facebook一樣。如何「修復」它們之間的空間。

https://codepen.io/weber93/pen/owwBQY

header { 
    position: fixed 0 0; 
    background-color: #3b5998; 
    background-image: linear-gradient(#4e69a2, #3b5998 50%); 
    border-bottom: 1px solid #133783; 
    height: 83px; 
    width: 100vw; 
} 

header .container { 
    display: flex; 
    flex-flow: row nowrap; 
    align-items: center; 
    justify-content: space-between; 
    } 

/*///// Header Logo ///////*/ 
header #logo { 
    height: 40%; 
    margin-top: 17px; 
    margin- 
} 

header img { 
    height: 100%; 
} 

/*///// Header Login Bar ///////*/ 

#login { 
    margin-top: 6px; 
    font-size: .8rem; 
} 

#login thead { 
    color: #ffffff; 
    font-size: .8rem; 
} 

#login thead td { 
    padding-left: 3px; 
} 

#header-input { 
    margin-bottom: 5px; 
} 

#header-input input{ 
    margin-right: 14px; 
    margin-top: 6px; 
    width: 150px; 
    height: 23px; 
} 

#login input{ 
    border: solid 1px #1d2a5b; 
    padding: 2px; 
} 

#login input:focus{ 
    outline-color: rgb(240,119,70); 

} 

#login button { 
    background-color: #4267b2; 
    border: 1px solid #29487d; 
    border-radius: 2px; 
    color: #ffffff; 
    font-weight: 600; 
    padding: 3px 6px; 
} 

#login button:hover { 
    background-color: #365899; 
    } 

#forgot-account { 
    padding-top: 6px; 
} 

#forgot-account a{ 
    color: #9cb4d8; 
    text-decoration: none; 
} 

#forgot-account a:hover { 
    text-decoration: underline; 
} 

回答

2

如果您正在尋找兩個元素,然後使用固定的單位,如像素之間的固定距離。

您的佈局將不適用於justify-content,因爲此屬性只是在容器中分配可用空間。隨着屏幕重新調整大小時空間大小發生變化,分配的空間量也會發生變化。換句話說,大多數flex屬性(包括justify-content)的設計都是爲了創建靈活的–不固定的–佈局。

相反,嘗試這樣的事:

header .container { 
    display: flex; 
    flex-flow: row nowrap; 
    align-items: center; 
    /* justify-content: space-between; */ 
    } 

header #logo { 
    height: 40%; 
    margin-top: 17px; 
    margin-right: 450px; /* new */ 
} 

revised codepen

或者,你可以插入徽標和登錄之間的第三,無形的柔性項目。這個「spacer」項目可以設置爲:flex: 0 0 450px

+1

謝謝。我認爲運行一個無形的彈性項目可能是這種情況,但不確定是「最佳實踐」還是我錯過了某些東西。這非常有幫助。 –