www.webdeveloper.com
Results 1 to 3 of 3

Thread: vertically align div within div

  1. #1
    Join Date
    Aug 2007
    Posts
    50

    Red face vertically align div within div

    css newbie here... I am trying to center an object vertically within a div that is relative to the parent div. Here is my relevant css:

    #top {
    text-align: center;
    height: 70%;
    background-color: Blue;
    }
    #centered
    {
    border: 0;
    background-color: White;
    height: 50%;
    width: 50%;
    position: absolute;
    left: 25%;
    top: 25%
    }

    I am trying to center the "centered" div vertically within the "top" div. As of right now the "centered" div is vertically centered in the page. I need everything based off percentage, not pixels or ems...

    My html is below:

    <div id="top">
    <div id="centered">
    <object id="Player" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="352" height="240">
    <param name="URL" value="images/wood_is_life.avi"/>
    <param name="autoStart" value="true"/>
    <param name="uiMode" value="none"/>
    </object>
    </div>
    </div>

    Any help would be greatly appreciated...

  2. #2
    Join Date
    Apr 2005
    Location
    Essex, United Kingdom
    Posts
    187
    Vertical alignment is always a problem with CSS layouts. This is the only way i can think of achieving it. It requires you to know the height of the object you want to centre vertically, but that is not a problem in your case, as you do know the height.

    Basically, follow these steps:
    1. Set the position of the centred object to relative. This will allow you to move it relative to it's parent div.
    2. Set the top to 50%. This will align the top of the centred object to the centre of the parent div.
    3. Finally, set the top margin to negative half the height of the centred div. This will move the centred div so the centre will be aligned with the centre of the parent div.
    For example:

    HTML Code:
    <html>
    <head>
    <style>
    #top {
      background:yellow;
      height:500px;
      width:200px;
      text-align:center
    }
    
    #centred {
      position:relative;
      width:50px;
      height:50px;
      background:red;
      top:50%;
      margin-top:-25px
    }
    </style>
    </head>
    <body>
    <div id="top">
      <div id="centred"></div>
    </div>
    </body>
    </html>
    Hope this helps

  3. #3
    Join Date
    Aug 2007
    Posts
    50
    Thanks for the response, the problem is that I cannot set a fixed dimension on the "top" div. I need this div to cover 70% of the screen no matter what the screen resolution...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles