当页面大于屏幕时,如何在屏幕中间放置div [英] How to position a div in the middle of the screen when the page is bigger than the screen

查看:329
本文介绍了当页面大于屏幕时,如何在屏幕中间放置div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我使用类似于以下内容的div来获取位于屏幕中间的div:

Hi I'm using something similiar to the following to get a div positioned in the middle of the screen:

<style type="text/css"> 
#mydiv {
    position:absolute;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

</style>


<div id="mydiv">Test Div</div>

但是,这样做的问题是它将项目放在页面中间而不是屏幕。所以如果页面是几个屏幕高,我在页面的顶部(部分的顶部显示在屏幕上),当我使div出现甚至不是在屏幕上。

However the problem with this is it positions the item in the middle of the page not the screen. So if the page is a few screen high and I'm at the top of the page (the top part of the part is displayed on the screen) when I make the div appear it's not even on the screen. You have to scroll down to view it.

有人可以告诉我如何让它出现在屏幕中间?

Can someone please tell me how you'd make it appear in the middle of the screen?

推荐答案

只需添加 position:fixed ,即使向下滚动也会保留。请参见 http://jsfiddle.net/XEUbc/1/

just add position:fixed and it will keep it in view even if you scroll down. see it at http://jsfiddle.net/XEUbc/1/

#mydiv {
    position:fixed;
    top: 50%;
    left: 50%;
    width:30em;
    height:18em;
    margin-top: -9em; /*set to a negative number 1/2 of your height*/
    margin-left: -15em; /*set to a negative number 1/2 of your width*/
    border: 1px solid #ccc;
    background-color: #f3f3f3;
}

这篇关于当页面大于屏幕时,如何在屏幕中间放置div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆