如何在屏幕中心放置绝对div

时间:2013-12-12 09:35:25

标签: javascript jquery html css

我创建了一个带有小图像的页面,我希望在点击它然后在绝对div中打开大图像时,它确实可以正常工作。但是在窗口显示页面的底部,并且点击小图像的时候在屏幕的顶部看,并且不喜欢它。我想每次都出现在画面的中心,请在这个页面看到: http://www.3dcreate.ir/New3DCreate/Pages/Gallery/3DGallery/3dg_Chosen.php

我的代码示例是:

HTML CODE:

<!-- This is Div of Large Image and Background Shade -->
<div class="BackgroudShade"></div>
<div class="DivOfImage"><img class="LargeImage"/></div>

CSS代码:

.DivOfImage {
    border: 8px solid #FFF;
    color:#FFF;
    background-color:#FFF;
    border-radius:10px;
    position:absolute;
}

JQuery CODE:

function LoadShowDiv () {
    $('.BackgroudShade').slideDown(800);   // shade of background will be visible
    $(".DivOfImage").show();               // Div of Large Image will be visible          
    // When Image loaded successful then set width,height and top,left of Large Image Div 
    // but i want set top,left when screen is scroll down to bottom of page
    // then show Div at middle of screen in every time
    $('.LargeImage').load(function() {     
       $('.DivOfImage').width($('.LargeImage').width());
       $('.DivOfImage').height($('.LargeImage').height());
       var LeftPostion = (WidthOfScreen - $('.LargeImage').width()) / 2;
       var TopPostion = (HeightOfScreen - $('.LargeImage').height()) / 2;
       $(".DivOfImage").offset({ top: TopPostion, left: LeftPostion});
       $('.LargeImage').show(1000);
    })
}

$('#SmallImage').click(function(){
    $('.LargeImage').attr('src','LargeImage.jpg');
    LoadShowDiv();
})

3 个答案:

答案 0 :(得分:2)

您不需要使用所有这些JS来计算并在屏幕中间显示图像。 您可以使用CSS来设置样式和位置,然后使用JS来隐藏/显示。你的位置:固定;然后,您可以更轻松地在屏幕上定义位置。

尝试这样的事情:

CSS
.LargeImage {
    position: fixed;
    top: 50%;
    left: 50%;
    margin-top: -(half of image height);
    margin-left: -(half of image width);
}

这会将图像保留在屏幕中央

答案 1 :(得分:1)

leftright添加为0并使用margin:0 auto

.DivOfImage {
    border: 8px solid #FFF;
    color:#FFF;
    background-color:#FFF;
    border-radius:10px;
    position:absolute;
    left:0;
   right:0;
   margin:0 auto
}

这是为了使div水平居中而不是垂直居中。

答案 2 :(得分:0)

如果您想将其水平和垂直居中放置在整个屏幕上并完全忽略网页上的其他元素,您可以使用

#yourElement{
    position: fixed;
    height: 40px;
    width: 20px;
    left: 50%;
    top: 50%;
    margin-left: -10px; //half of width
    margin-top: -20px; //half of height
}

这会将元素放在用户屏幕的中心。

相关问题