2010-10-19 76 views
2

我在屏幕上居中显示图像。我需要在图像上方显示一些文字,并且我想设置相对于图像的文字坐标。在图像上定位文字

如果用户有不同的分辨率:

  • 图像始终位于浏览器的顶部和中心。
  • 文本将在图像中的相同位置。

我曾尝试:

<style type="text/css"> 
    #l1 { 
     position: relative; 
     left: 20px; 
     top: 30px; 
     color: #03C; 
    } 
</style> 


<div align="center"> 
    <div id="l1" align="left"> 
     some 
    </div> 
<img src="some.jpg" width="1024" height="788" /> 
</div> 

但它不工作。我怎样才能实现我的目标?

+0

您的图片总是有相同的尺寸? – MatTheCat 2010-10-19 09:20:51

+0

是的,总是一样的。 – demas 2010-10-19 09:24:19

回答

2

设置文本是position:absolute和包含div是position:relative

而且还使用中心的利润率,而不是过时的align属性格..

<style type="text/css"> 
    .container{ 
      position:relative; 
      margin-left:auto; 
      margin-right:auto; 
      width:1024px;} 
    #l1 { 
     position: absolute; 
     left: 20px; 
     top: 30px; 
     color: #03C; 
     text-align:left; 
    } 
</style> 


<div class="container"> 
    <div id="l1"> 
     some 
    </div> 
<img src="some.jpg" width="1024" height="788" /> 
</div> 
+0

我试过了,但它不起作用 – demas 2010-10-19 09:23:47

+0

@demas,我有一个错误..我需要在容器div上设置尺寸以匹配图像..现在它应该没事.. – 2010-10-19 09:26:08

+0

谢谢。这就是我想要的:) – demas 2010-10-19 09:28:39

1

我会做这样的:

<!doctype html> 
<html> 
<head> 
    <title></title> 
    <style type="text/css"> 
     /*reset default margins, paddings, set body font*/ 
     html,body,h1,h2,h3,h4,h5,p,ul,li,form,button { margin:0; padding:0 } 
     body { font:normal 62.5% tahoma } 

     #my-image { 
      width:1024px; height:788px; 
      background:url(some.jpg); /* use image as background */ 
      margin:0 auto; /* this centers the div in the browser horizontally */ 
      position:relative; /* set positioning context for children */ 
     } 

     #my-text { 
      position:absolute; 
      left:0px; top:0px; /* left and top are with respect to the parent div */ 
     } 
    </style> 
</head> 
<body> 

    <div id="my-image"> 
     <div id="my-text">some text</div> 
    </div> 

</body> 
</html> 
+0

我在#my-text中改变了左边和上边,但没有改变。 – demas 2010-10-19 09:27:24

+0

0不需要单位。如果你把它改为0以外的值,你需要添加'px' ..所以试试这样:'20px' – 2010-10-19 09:38:51

+0

对不起:)这是我的错误。 – demas 2010-10-19 09:43:17