【问题标题】:CSS Vertically & Horizontally Center Div [duplicate]CSS垂直和水平居中的Div [重复]
【发布时间】:2012-01-07 12:28:17
【问题描述】:

我有一个包含 ASP.NET 表单的弹出窗口,单击链接“请求信息”并出现该表单。

但是,带有“请求信息”链接以触发弹出窗口的页面内容很多,因此需要滚动才能看到该链接。

如果用户滚动阅读内容,我需要让div 始终居中,否则如果他们不滚动,弹出窗口仍会居中显示在屏幕上。

div绝对定位,整个页面宽度为960px,边距设置为0 auto

【问题讨论】:

    标签: html css


    【解决方案1】:

    如果 div 具有固定的宽度和高度,请使用: (如果宽度=120 像素,高度=80 像素)

    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -60px; /* negative half of the width */
    margin-top: -40px; /* negative half of the height */
    

    【讨论】:

    • 这会将 div 放在右下角,而不是居中。您需要将边距设为负数。
    • 他们现在是负面的......
    【解决方案2】:

    如果您的弹出 div 具有固定大小,那么您可以使用这个 CSS:

    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto; /* this requires a fixed size */
    

    否则你必须摆弄 display: table-cell;之类的。

    【讨论】:

      【解决方案3】:

      这是你想要做的吗? http://jsfiddle.net/Hrwf8/

      这里的关键是将left和top样式设置为50%,并将margin-left和top设置为div宽度和高度的一半的负数。这当然要求你的 div 有一个固定的大小。

      【讨论】:

        【解决方案4】:

        使用位置:固定;为此,使用 0 表示顶部、左侧、右侧和底部,并给 div 一个 display:table-cell;同样,像这样,设置 text-align:center;和垂直对齐:中间;将使里面的所有东西都出现在中间,没有像负边距这样的像素精确黑客。

        【讨论】:

        • 好的,left 和 top 的值是多少?
        • @JordyVialoux 更新了答案。
        【解决方案5】:

        在您的 CSS 中:

        .ClassCenter {
            position: absolute;
            left: 50%;
            top: 50%;
        }
        

        来源: http://demo.tutorialzine.com/2010/03/centering-div-vertically-and-horizontally/demo.html

        【讨论】:

        • 那只是将左上角放在中心,框仍然不会居中
        猜你喜欢
        • 2012-12-16
        • 2013-10-14
        • 2011-05-18
        • 2013-10-05
        • 2015-08-29
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        • 2011-02-18
        相关资源
        最近更新 更多