471,044 Members | 937 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,044 software developers and data experts.

Center a <DIV> with Javascript.

Hi All,

I'm trying to center a StyleSheet like below :

<div id="CenterThis" style="position:absolute; top:40px; left:70px;">This
should be centered</div>
With this code :
<script language="JavaScript" type="text/javascript">
var ScreenW = document.documentElement.offsetWidth;
document.write(ScreenW);
</script>

I can get the screenwidth, but how would I combine this with the div code so
that it will be centered??

Any suggestions/help is welcome!

Thanks!

Regards,
Steven.
Jul 20 '05 #1
1 11133
News wrote on 08 okt 2003 in comp.lang.javascript:
<script language="JavaScript" type="text/javascript">
var ScreenW = document.documentElement.offsetWidth;
document.write(ScreenW);
</script>


This will not work, I think.

The offsetWidth is only available when the page is rendered in the browser
and a subsequent document.write destroys the rendering and starts a new
page.

Try this:

<div id="myElement">x</div>

<script type="text/javascript">
var myoffsetWidth = document.getElementById("myElement").offsetWidth;
document.getElementById("myElement").innerHTML = myoffsetWidth + "px"
</script>

IE6 tested.

--
Evertjan.
The Netherlands.
(Please change the x'es to dots in my emailaddress)
Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by Josef K. | last post: by
8 posts views Thread by Primal-oooze | last post: by
1 post views Thread by Carl | last post: by
13 posts views Thread by Mark | last post: by
5 posts views Thread by chakradhari.ashish | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.