Best Way To Centre Dynamic Div In Middle Of Page
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;
}
Solution 2:
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:
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() {
functionupdateDivPosition() {
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
});
Post a Comment for "Best Way To Centre Dynamic Div In Middle Of Page"