【问题标题】:How to prevent a vertically-centered div from disappearing off of small screens如何防止垂直居中的 div 从小屏幕上消失
【发布时间】:2013-01-30 08:52:49
【问题描述】:

我有以下 CSS 用于在页面上垂直居中 DIV(以及水平居中)。如果浏览器窗口的高度小于 600px,我希望窗口能够滚动以显示整个 DIV。但是,DIV 只是以页面为中心,超出浏览器高度的任何内容都被隐藏了——没有滚动条。有什么方法可以让用户滚动到这些现在隐藏的区域?

#container{
    width:800px;
    height:600px;
    position:absolute;
    margin-top:-300px;
    top:50%;
    margin-left:-400px;
    left:50%;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    max-widthmax-height 添加@media 查询

    @media (max-width: 800px) {
        #container {
            left: 0px;
            margin-left: 0px;
        }
    }
    
    @media (max-height: 600px) {
        #container {
            top: 0px;
            margin-top: 0px;
        }
    }
    

    JSFiddle

    【讨论】:

      【解决方案2】:

      你也可以尝试添加

      overflow:scroll;
      

      overflow 属性指定如果内容溢出元素的框会发生什么。

      【讨论】:

        【解决方案3】:

        检查这个

        #container{
        position: absolute;
        top: 50%;
        left: 50%;
        width: 30em;
        height: 18em;
        margin-top: -9em;
        margin-left: -15em;
        border: 1px solid #ccc;
        background-color: #f3f3f3;
        }
        

        【讨论】:

        • 您需要根据需要更改高度、宽度、边距
        【解决方案4】:

        使用这个

          #container
            {
            width:800px;
            height:600px;
            margin-left:auto;
            margin-right:auto;
            }
        

        【讨论】:

        • 我已经将 margin-left 设置为特定的数量以使 DIV 水平居中。这将如何影响 DIV 的垂直可见性?
        【解决方案5】:

        您正在使用position: absolute;,因此除非您将div 设置为min-widthmargin 设置为auto,否则无法实现此目标

        <div>vertically centered div</div>
        <div>min-width div</div>
        
        div:nth-of-type(2) {
           min-width: 1000px; /*Change accordingly*/
        }
        

        【讨论】:

        • 这个我试过了,但是好像没有效果。您能否发布一个 jsfiddle 脚本或解释第二个 DIV 如何影响垂直居中 DIV 的可见性?
        猜你喜欢
        • 1970-01-01
        • 2012-05-27
        • 2017-09-09
        • 2014-05-27
        • 2015-05-06
        • 1970-01-01
        • 2021-05-01
        • 2017-03-20
        • 2011-05-23
        相关资源
        最近更新 更多