2016-07-05 132 views
0
<html> 
    <head> 
    <h1>Hello.</h1> 
    </head> 
    <link rel="stylesheet" type="text/css" href="butters.css"> 
    <link href="https://fonts.googleapis.com/css?family=Galada" rel="stylesheet"> 
    <body></body> 
</html> 

+如何在CSS中垂直和水平居中標題?

h1{ 
    font-family: 'Galada', cursive; 
    font-size: 400%; 
    position: relative; 
    top: 50%; 
    left: 50%; 
    transform: translateY(-50%); 
} 

Link to fiddle. I pretty much followed this tutorial.

我雖然發現問題與它,因爲它創造了水平滾動條,這是我不想,我不相信這是水平居中。我只是想讓它在屏幕中間輕拍一下,不管屏幕大小如何,但我不確定要做什麼CSS。

回答

1

我改變你的CSS:

h1{ 
    font-family: 'Galada', cursive; 
    font-size: 70px; 
    transform: translate(-50%,-50%); 
    position: absolute; 
    top: calc(50% - 35px); 
    left: 50%; 
} 
+0

謝謝! [它現在幾乎可以工作](https://jsfiddle.net/6oyq0szs/1/),但似乎儘管有50%,但頂層空間比底層空間要多。你也看到了嗎?還是我只是妄想? – somanyerrorswhy

+0

是的,你說得對。它發生是因爲元素的頂部是有效地居中的東西。我改變了CSS,以像素爲單位指定'font-size',並用字體大小的一半來計算'top'作爲折扣。 –

0

嘗試改變的位置是:相對於位置:絕對

0

兩件事情 - 首先,你必須在你的頭上,這是無效的H1,你要來移動你的身體。從那裏,你需要給這個50%的身體定位。它還需要獲得位置:絕對的左側和頂部才能正常工作。之後,您可以同時執行translateX和translateY以使它在兩個軸上居中。下面的例子!

h1{ 
    font-family: 'Galada', cursive; 
    font-size: 400%; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translateY(-50%) translateX(-50%); 
} 
body{ 
    width: 100%; 
    position: relative; 
} 

https://jsfiddle.net/will0220/pw4j2m36/1/

0

您需要通過邊距頂部相對元素來代替:

h1{ 
 
    font-family: 'Galada', cursive; 
 
    font-size: 400%; 
 
    position: relative; 
 
    margin-top: 50%; 
 
    left: 50%; 
 
    transform: translateY(-50%); 
 
}
<h1>Hello.</h1>

0
The easiest way to align text horizontally is "text-align: center", if You know vertical height, You can align vertically with "line-height: (value)px" 

HTML 
<body> 
    <h1>Hello.</h1> 
</body> 

CSS 
html, body { 
    margin: 0; 
    padding: 0; 
    width: 100%; 
    height: 100%; 
} 

h1 { 
    font-family: 'Galada', cursive; 
    font-size: 400%; 
    text-align: center; 
    margin-top: 50%; 
}