无法居中文字?

时间:2014-04-18 06:11:51

标签: css html text center

我一直试图通过在我的HTML中使用top: 50%; left: 50%;来在我的目标网页上居中显示一段文字,但由于某种原因它不在中心?这是我在<body>标签后使用的html -

<div style="position: absolute; top:50%; left:50%; width:500px; height:25px"><font size="4" color="white">My Text Here</font></div>

除了google font css代码之外,我没有任何css可以使用它。 (见下文)

 body {
    font-family: 'Open Sans', sans-serif;
    font-size: 48px;
  }

这就是我网站上的样子 -

http://s11.postimg.org/l1iwonjz7/frigofdhjvuidrh.jpg

P.S我没有那么多的编码知识,所以如果我说的话毫无意义,那就说吧。

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以尝试以下代码:

Working Demo

<div style="position: absolute; top:50%; left:50%; width:500px; height:25px; margin-  left:-250px; margin-top:-13px;background:#ccc;"> 
<font size="4" color="white">My Text Here</font></div>

答案 1 :(得分:0)

你只需要设置:

文字对齐:中心;

 <div style="position: absolute; top:50%; left:50%; width:500px; height:25px;text-align:center;border:1px solid"><font size="4" color="white">My Text Here</font></div>

如果这有助于你不要忘记接受答案;)

答案 2 :(得分:0)

试试这个。更好的兼容性和更强大的功能。

<div style="position: absolute; top:50%; width:100%; height:1em; margin-top: -.5em; color: white; font-size: 10px; text-align: center;">My Text Here</div>

以上内容应使文本完全对齐页面中心。诀窍是&#39; text-align:center;&#39;。标记的所有子文本都将由浏览器自动居中。

另外,只是注意:通常认为使用不推荐的标签(例如字体标签)是不好的做法,因为它的结果可以使用CSS实现。我没有使用它并在CSS中使用它的一般等价物。