2017-08-07 27 views
0

Following code按預期工作(塊居中)在Chrome和Firefox,但在Safari子容器稍微偏離:如何在Safari中將flexbox容器中的固定內容居中?

#container { 
    width: 100%; 
    background: yellow; 
    height: 20px; 
    position: absolute; 
    top: 0; 
    left: 0; 
    display: flex; 
    justify-content: center; 
} 

#content { 
    padding: 0px; 
    background: linen; 
    position: fixed; 
} 

enter image description here enter image description here

我的問題是 - 如何中心「的立場:固定「元素在」顯示器:flexbox「家長在Safari?

回答

1

帶有position: fixed(或position: absolute)的元素在Safari中的行爲與他們在Chrome/Firefox中的行爲不同。

在Safari中居中柔性項目,你需要使用transform: translate

Updated codepen

棧片斷

#container { 
 
    width: 100%; 
 
    background: yellow; 
 
    height: 20px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    display: flex; 
 
    justify-content: center; 
 
} 
 

 
#content { 
 
    padding: 0px; 
 
    background: linen; 
 
    position: fixed; 
 
    left: 50%; 
 
    transform: translateX(-50%); 
 
}
<div id="container"> 
 
    <div id="content">THIS CONTENT IS NOT CENTERED IN SAFARI</div> 
 
</div>

+0

是的,這看起來像最廉價有效的解決方案。我想知道爲什麼Safari和Chrome會有所不同 - 是故意的(就像解釋一些CSS規範不同)或者只是一個錯誤。 – shabunc

+1

@shabunc這是一個在Flexbox模型中做出的改變,其中一些瀏覽器還沒有趕上。這是一個徹底的解釋https://stackoverflow.com/questions/32991051/absolutely-positioned-flex-item-is-not-removed-from-normal-flow-in-firefox-ie1 ...這可能還有資格作爲副本 – LGSon