Domanda

I've been trying to center a piece of text on my landing page, by using top: 50%; left: 50%; in my html, but for some reason it's not in the center? Here's the html I'm using after the <body> tag-

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

I don't have any css to go with it apart from the google font css code. (see below)

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

This is what it's looking like on my website-

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

P.S I don't have that much knowledge of coding so if what I said made no sense, just say.

Thanks!

È stato utile?

Soluzione 2

Try this instead. Better compatiblity and more robust.

<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>

The above should align the text exactly in the center of the page. The trick is 'text-align: center;'. All child text of a tag will be automatically centered by the browser.

Also, just a note: its usually considered bad practice to use deprecated tags such as the font tag since its results can be achieve using CSS. I refrained from using it and used its general equivalent in CSS.

Altri suggerimenti

You can try below code:

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>

You just need to set:

text-align:center;

 <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>

If this helps you dont forget to accept answer ;)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top