2016-05-23 55 views
1

下此代碼運行按預期在Chrome:絕對元素導致行爲怪異火狐

請將鼠標懸停在藍色球的動畫:

<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <style> 
 
    .container { 
 
     position: relative; 
 
     width: 100%; 
 
     height: 200px; 
 
     border: thin solid #6D6; 
 
     overflow: hidden; 
 
    } 
 
    h2 { 
 
     position: absolute; 
 
     border-radius: 100%; 
 
     background-color: blue; 
 
     height:100px; 
 
     width: 100px; 
 
     transition:all 1s ease-out; 
 
     margin: auto; 
 
     left: 0; 
 
     top: 0; 
 
     bottom: 0; 
 
     right: 0; 
 
    } 
 
    
 
    h2:hover { 
 
     height: 300px; 
 
     width: 300px; 
 
    } 
 
    </style> 
 
</head> 
 

 
<body> 
 
    <div class='container'> 
 
    <h2></h2> 
 
    </div> 
 
</body> 
 

 
</html>

但中間的球在Firefox中擴展到底部,我必須設置頂部或底部才能使其回到正確的位置。是否有什麼方法可以讓它保持在中間位置,而不像Chrome中那樣分配頂部和底部值?

回答

0

一個很好的把戲,在一個相對定位的容器中間居中塊元素,使用top: 50%transform: translateY(-50%)

它需要IE9 +

.container { 
 
     position: relative; 
 
     width: 100%; 
 
     height: 200px; 
 
     border: thin solid #6D6; 
 
     overflow: hidden; 
 
    } 
 
    h2 { 
 
     position: relative; 
 
     border-radius: 100%; 
 
     background-color: blue; 
 
     height: 300px; 
 
     width: 200px; 
 
     margin: auto; 
 
     top: 50%; 
 
     transform: translateY(-50%); 
 
    }
<div class='container'> 
 
    <h2></h2> 
 
    </div>

的jsfiddle演示:https://jsfiddle.net/oujab44t/1/

+0

它的東西,我不想做的,額外的定位。因爲您可以看到chrome將元素保留在中間,而其擴展卻沒有任何額外的設置。也許這是Firefox的默認行爲。 –

+0

@RyVan只是因爲某些事情在Chrome中表現出某種特定的方式,並不意味着這是標準。這個想法是編寫在任何地方都運行相同的代碼。您正在使用Chrome進行開發,並抱怨Firefox顯示的內容有所不同。如果您是第一次使用Firefox開發的,則不會遇到此問題。我的建議仍然存在這是我在很多地方看到的一個很好的做法。這不是黑客。 – Narxx

+0

感謝的人,但我需要知道的是天氣有可能在Firefox中做類似的事情。 –

-4
<head> 
    <style> 
    .container { 
    to; 
    left: 0; 
    top: 0; 
    bottom: 0; 
    right: 0; 
    } 
    </style> 
</head> 
<body> 
    <div class='container'> 
    <h2></h2> 
    </div> 
</body> 
</html> 
+5

儘管此代碼片段可能會解決此問題,但[包括解釋](http://meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers)確實有助於提高帖子的質量。請記住,您將來會爲讀者回答問題,而這些人可能不知道您的代碼建議的原因。 – gunr2171

相關問題