在图像上定位文本

时间:2010-10-19 09:14:47

标签: html css

我的图像以屏幕为中心。我需要在图像上方显示一些文字,我想设置相对于图像的文本坐标。

如果用户的分辨率不同:

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

我试过了:

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

但它不起作用。我怎样才能实现目标?

2 个答案:

答案 0 :(得分:2)

将文字设置为position:absolute,将包含的div设置为position:relative

并且还使用边距而不是已弃用的align属性来居中div。

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

答案 1 :(得分: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>