【问题标题】:Center Content horizontally and vertically with scrollbars?使用滚动条水平和垂直居中内容?
【发布时间】:2011-12-23 03:04:27
【问题描述】:

我有一个宽度:400px 和高度:300px 的 div 在 div 中我将插入一些应该水平和垂直对齐的文本。

如果 div 内的文本比 div 大,它应该显示滚动条。这是一张显示我的意思的图片:

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    以下适用于 webkit & geko & IE8 以上。如果您需要旧版 IE 兼容性,请尝试使用以下一些技术进行垂直居中:http://blog.themeforest.net/tutorials/vertical-centering-with-css/Vertically and Horizontally Center Image inside a Div, if you don't know Image's Size?

    <div style="height:300px; overflow-y:auto; border:solid 1px #CCC;  width:400px;">
        <div style="display:table-cell; vertical-align:middle; height:300px; text-align:center; width:400px;">
            test
        </div>
    </div>
    

    【讨论】:

    【解决方案2】:

    您可能希望将 div 用作容器,然后将文本放入另一个 div 您可能还想查看jscrollpane

    div.container {
    overflow: auto;
    text-align: center;
    }
    
    
    
    <div class="container">
    <p align="center">
    <h2>Heading 1</h1>
    <h2>Heading 2</h2>
    </p>
    </div>
    

    同时尝试为你的容器设置一个固定的高度,这样你就可以得到滚动条

        div.container {
    max-height: 200px
    }
    

    cronoklee 的帖子也很好用,你可能想结合这两种方法来得到你想要的东西

    【讨论】: