2011-03-18 45 views
0

我有一個網站,其背景圖像在<div>元素的另一個<div>元素中包含文本。 由於文本發生變化,我需要動態地對其進行居中。 到目前爲止,我有這個,但它仍然是左對齊:使用CSS背景圖像中的中心文本

<html> 
    <head> 
    <title>3D Text</title> 
<script> sets the text dynamically</script> 
<style> 

#Layer { 
    width: 320px; 
    height: 480px; 
    position: absolute; 
    border-style: none; 
    top: 0px; 
    left: 0px; 
    z-index: 0; 
    } 

#clock { 
    position: relative; 
    font-family: Helvetica Neue; 
    color: black; 
    font-size: 80px; 
    text-align: center; 
    opacity: 1; 
    float: left; 
} 

.stretch { 
    width:100%; 
    height:100%; 
} 




</style> 

</head> 

<body onload="onLoad()"> 

     <div id="Layer"><img src="bg2.png" class="stretch"/></div> 

      <div id="clock"> 
       <script language="JavaScript">setText(); setInterval("setText()", 1000)</script> 
      </div> 

</body> 
</html> 

回答

1

你的時鐘DIV不是DIV層裏面。

試試這個:

<html> 
    <head> 
    <title>3D Text</title> 
<script> sets the text dynamically</script> 
<style> 

#Layer { 
    width: 320px; 
    height: 480px; 
    border-style: none; 
    background-image: url(bg2.png); 
    } 

#clock { 
    font-family: Helvetica Neue; 
    color: black; 
    font-size: 10px; 
    text-align: center; 
    opacity: 1; 
} 

.stretch { 
    width:100%; 
    height:100%; 
} 




</style> 

</head> 

<body onload="onLoad()"> 

     <div id="Layer"> 

      <div id="clock"> 
       12:00PM 
      </div> 
</div> 
</body> 
</html> 
+0

共做了工作。除了它必須是'background-image:url(bg.png);' – tzippy 2011-03-19 12:05:19

+0

由於我的背景圖像是960 x 640像素,我還需要將其縮小50%以適合我的「圖層」-div。有沒有一個CSS屬性來做到這一點? – tzippy 2011-03-20 12:43:56

+0

background-size是我正在尋找的財產。 – tzippy 2011-03-21 09:28:22

0

由於您使用float: left。浮動元素只使用它需要的空間。

您必須設置width屬性#clock才能完成此項工作。

0

我相信你有一個的寬度爲您的DIV爲它對齊文本