Skip to content Skip to sidebar Skip to footer

Best Way To Centre Dynamic Div In Middle Of Page

I know this sort of thing has been asked a lot but I want to be able to centre a div in the middle of the page and have it always stay in the middle of the page no matter how wide

Solution 1:

Unless I'm missing something you can forgo the JavaScript and use plain CSS:

div {
    position:absolute;
    background:red;
    width:20%;
    height:20%;
    top:0;
    bottom:0;
    left:0;
    right:0;
    margin:auto;
}

jsFiddle example


Solution 2:

Here is you go.

It should be noted that this answer is more about concepts than giving you the answer outright.

Now, you see the 'div#b' section of the CSS? To keep everything in the center, simply write a script that keeps the margin-top value -50% of the height. And that's it!

Example: (currently) height = 60, margin-top = -30px (changed for height = 100) height = 100, margin-top = -50px

div#a
{
    width: 300px;
    height: 300px;
    border-width:1px;
    border-style: solid;

    /* important stuff below */
    display: inline-block; 
}

div#b
{
    width: 60px;
    height: 60px;
    background-color: red;

    /* important stuff below */
    position: relative;
    margin: -30px auto 0 auto;
    top: 50%;    
}

Solution 3:

Here's a codepen:

Check it out.

Most of your styles aren't necessary, and javascript is definitely unnecessary. The key to vertical centering is display: table. It requires some nesting, so I altered your structure as well.


Solution 4:

In jQuery you can use .width() and .height() methods as they returns computed width in pixels, not in percentage + you will need to listen window resize event. For example like this:

$(function() {
    function updateDivPosition() {
        var myWidth = $( '.myDivHere' ).width()
          , myHeight = $( '.myDivHere' ).height();
        $( '.myDivHere' ).css( { 
            marginLeft: -( parseInt( myWidth, 10 ) / 2 ) + 'px',
            marginTop: -( parseInt( myHeight, 10 ) / 2 ) + 'px'
        });
    }
    updateDivPosition(); // first time set correct position on onload
    $( window ).resize( updateDivPosition ); // update on window resize
});

jsFiddle demo


Post a Comment for "Best Way To Centre Dynamic Div In Middle Of Page"