How to reposition a div inside another?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Undisclosed Mem
    New Member
    • Jan 2011
    • 1

    #1

    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:
    Code:
    body {
    	overflow-x: hidden;
    	background-color: #ededed;
    }
    #testContainer {
    	height: 400px;
    	width: 1100px;
    	background-color: #ffffff;
    	
    	margin-top: -8px;
    	margin-left: auto;
    	margin-right: auto;
    }
    #testDiv {
    	color: black;
    	text-align: left;
    	font-family: "Helvetica Neue";
    	font-style: italic;
    	font-weight: bold;
    	font-size: 24px;
    	height: auto;
    	max-height: 400px;
    	width: 500px;
    }
    HTML/JAVASCRIPT:
    Code:
    <html>
    <head>
    	<link rel="stylesheet" type="text/css" href="style.css" media="screen"/>
    </head>
    <body>
    <div id="testContainer">
    	<div id="testDiv">"Here is a sample of text which gives offsetHeight a real value."</div>
    </div>
    
    <script language="javascript" type="text/javascript">
    	var divH = document.getElementById('testDiv').offsetHeight;
    	var divT = (400-document.getElementById('testDiv').offsetTop)/2;
    	document.getElementById('testDiv').offsetTop = divT;
    </script>
    
    </body>
    </html>
    Last edited by Niheel; Jan 30 '11, 12:42 AM.
  • JKing
    Recognized Expert Top Contributor
    • Jun 2007
    • 1206

    #2
    You cannot set the offsetTop property. It only returns the value.

    Try setting a top margin instead.
    Code:
        document.getElementById('testDiv').style.marginTop = divT;
    Also there are CSS methods out there for centering an element vertically.

    Comment

    Working...