center div horizontally without "jumping"
Further to this question, I added some JavaScript to this page to place the #container
div centrally.
However, what now happens is:
- page loads in default position
- JavaScript kicks in and repositions
#container
centrally
Because the main images are reasonably large, there's a noticeable delay before the content "jumps" into a central position.
As I mentioned in the original post, the normal way to center content horizontally is
#container { margin: 0 auto }
But I can't do this, because the layout (which I did not write), unnecessarily uses a lot of absolute posit开发者_运维问答ioning.
Is there any way I can eliminate this jumping effect, while keeping the content centrally located?
Thanks!
Its a bit dirty but dont put your javascript on the document onload event. Place it straight after the closing tag of the end div. This will make it less noticeable
If you know the width of the container you can always center it the absolute positioning way:
#container { position: absolute; left: 50%; margin-left: <negative width divided by 2>; }
or set it to visibility:hidden; then after positioning it with set it to visible again with javascript. or even fade it in. only good if your visitors have js enabled. well you could set it to hidden in the onload event or after the div with js. so it'll still be there if js is deactivated.
Perhaps set the CSS to hide #container
on page load,
#container { display:none; }
then .fadeIn()
after the margins are set.
$(document).ready(function() {
setMargins();
$('#conatiner').fadeIn();
$(window).resize(function() {
setMargins();
});
});
Give your container a CSS attribute of "visibility:hidden" to start with, and have Javascript remove it after the positioning is done. It will look like that element loads slightly after the rest of the page, but it won't jump, and since you're not using "display:none", the container will push the rest of the content out of its bounding box even while its invisible, so the rest of the page won't jump when it loads either.
I'm not sure i entirely understand the question.. looking at the CSS, the div is centred horizontally anyway? consider this rule:
#container {
height:616px;
width:1024px;
left:50%;
margin-left:-512px;
margin-top:100px;
top: 0px;
}
it has a width of 1024px and we're saying position the left hand side right in the middle of the page. then the negative left margin equal to half of the width of the div causes the div to be centred.
Plus i notice some people recommend setting the div to visible: hidden
and then switching it back with JS after positioning the div. this is not good practice as a user without JS will never see anything. it is better to show by default, hide with JS, then re-show once everything else is complete.
please comment if i have misunderstood
精彩评论