469,936 Members | 2,487 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,936 developers. It's quick & easy.

How to reposition a div inside another?

I want to be able to center the div 'testDiv' inside the parent div 'testContainer' (which has a height of 400, but for the sake of simplification I just wrote 400 in as a constant. I'm very new to javascript so I have little idea of what I'm doing wrong.

CSS:
Expand|Select|Wrap|Line Numbers
  1. body {
  2.     overflow-x: hidden;
  3.     background-color: #ededed;
  4. }
  5. #testContainer {
  6.     height: 400px;
  7.     width: 1100px;
  8.     background-color: #ffffff;
  9.  
  10.     margin-top: -8px;
  11.     margin-left: auto;
  12.     margin-right: auto;
  13. }
  14. #testDiv {
  15.     color: black;
  16.     text-align: left;
  17.     font-family: "Helvetica Neue";
  18.     font-style: italic;
  19.     font-weight: bold;
  20.     font-size: 24px;
  21.     height: auto;
  22.     max-height: 400px;
  23.     width: 500px;
  24. }
  25.  
HTML/javascript:
Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3.     <link rel="stylesheet" type="text/css" href="style.css" media="screen"/>
  4. </head>
  5. <body>
  6. <div id="testContainer">
  7.     <div id="testDiv">"Here is a sample of text which gives offsetHeight a real value."</div>
  8. </div>
  9.  
  10. <script language="javascript" type="text/javascript">
  11.     var divH = document.getElementById('testDiv').offsetHeight;
  12.     var divT = (400-document.getElementById('testDiv').offsetTop)/2;
  13.     document.getElementById('testDiv').offsetTop = divT;
  14. </script>
  15.  
  16. </body>
  17. </html>
  18.  
Jan 29 '11 #1
1 1632
JKing
1,206 Expert 1GB
You cannot set the offsetTop property. It only returns the value.

Try setting a top margin instead.
Expand|Select|Wrap|Line Numbers
  1.     document.getElementById('testDiv').style.marginTop = divT;
  2.  
Also there are CSS methods out there for centering an element vertically.
Feb 1 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Georges Heinesch | last post: by
3 posts views Thread by mandible | last post: by
2 posts views Thread by gerotica | last post: by
3 posts views Thread by robin1983 | last post: by
7 posts views Thread by =?Utf-8?B?U2hpdmEgUmFtYW5p?= | last post: by
7 posts views Thread by 200dogz | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.