Search code examples
csshtml-tablevertical-alignment

Vertically centering with Tables


I have an iframe and a div inside a container. The two of them need to be vertically centered. After reading a few posts on tables to center, I gave it a try but to no avail. The iframe continues to stick to the top left border even though I have the iframe 'display' property set to 'table-cell' & 'vertical-align' to 'middle'.

The HTML code:

<!-- the container div -->
<div id="iframe_r_container">

<!-- iframe -->
            <iframe id="iframing" src="mannequin.html" frameborder="0" ></iframe>

<!--div-->      <div id="right_container">
                <div id="user_credit">
                    <h1><a href="#">Username</a></h1><br />
                     has <span id="credits">20,000</span> credits.
                </div>

                <div> <button id="template_button"><img src="images/Coutallure-WebApp/template_button.png" /><span>Templates</span></button> </div>
            </div>

And here is the CSS:

/* START OF IFRAME_R_CONTAINER */
#iframe_r_container {
    position: absolute;
    display: table;
    top: 48px;
    bottom: 38px;
    width: 960px;   
}

/* START OF IFRAME */
#iframing {
    display: table-cell;
    width: 640px;
    height: 480px;
    vertical-align: middle;
}
/* END OF IFRAME */


/* START OF RIGHT CONTAINER */
#right_container {
        display: table-cell;
        vertical-align: middle;
    width: 113px;
    margin: 20px;
}

I have been stuck at this for half a day today so any help would be immensely appreciated.


Solution

  • If you don't mind using another technique than table-cell centering, you can try something like this :

    #iframe_r_container {
        position: absolute;
        top: 48px;
        bottom: 38px;
        width: 960px;
    }
    
    /* START OF IFRAME */
    #iframing {
        position: relative;
        top: 50%;
        margin-top: -240px;
        width: 640px;
        height: 480px;
        float: left;
    }
    /* END OF IFRAME */
    
    
    /* START OF RIGHT CONTAINER */
    #right_container {
        position: relative;
        top: 50%;
        height: 113px;
        margin-top: -57px;
        margin-left: 670px;
        width: 113px;
    
    }
    

    It works here on my FF/mac but you'd have to test it on other browser.

    To center #right_container, you'd have to give it a heigh (here 113px) and set the negative margin-top accordingly.

    Also, you may want to give a min-height: 640px to #iframe_r_container to avoid the iframe overflowing outside of its container.