Center Text inside background image using CSS
I have a website with a backgroundimage in a <div>
element that has another <div>
element with text inside it.
Since the text changes, I need to center it dynamically.
So far I have this, but it is still left aligned:
<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>
Your clock div is not inside the Layer div.
Try this:
<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>
Because you are using float: left
. A floating element only uses the space it needs.
You will have to set the width
property on #clock
to make this work.
I believe you have to a have a width set for your div for it to align the text
精彩评论