2016-07-05 88 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%; 
}