html - 垂直和水平居中 overflow hidden 的div

标签 html css

我正在尝试将一个 div 垂直和水平居中到另一个具有 overflow: hiddendiv 我已经成功地水平居中居中,但不是垂直居中。

HTML

<div class="outer">
    <div class="inner">
        <div class="content">
            <p>Alot of content</p>
        </div>
    </div>
</div>

CSS

.outer {
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
}

.inner {
    display: inline-block;
    position: relative;
    bottom: -50%;
    right: -50%;
}

.content {
    position: relative;
    top: -50%;
    left: -50%;
    width: 500px;
    height: 500px;
}

FIDDLE

为什么我的 top: -50% 被忽略了,但我的 left: -50% 却按预期工作?

最佳答案

DEMO

其实fiddle并不清楚。

我不知道水平居中。所以我添加了它。但如果您不想要它,请跳过它。

对于垂直居中,你可以试试这个:

.outer {
    width: 100px;
    height: 100px;
    overflow: hidden;
    background: yellow;
}

.inner {
    display: inline-block;
    position: relative;
    text-align:center; //horizontal center
}

.content {
    position: relative;
    display: table-cell; //<-vertical center
    text-align: center; //<-vertical center
    width: 500px;
    height: 500px;
}

关于html - 垂直和水平居中 overflow hidden 的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24638379/

相关文章:

html - 转义 HTML 中的特殊字符

css - 我无法将 div 的内容居中

html - 网站文件不会更新(即使在硬刷新和清除缓存之后)

html - block /内联 block 内的页脚水平对齐

渐进式 Web 应用程序上的 Android 后退按钮关闭应用程序

javascript - Web Speech API 中语法的作用

html - 带有多列标题的水平列

css - 如何在div中将图像居中?

javascript - CSS 过渡到特定位置

html - nth-child 与 last-of-type 冲突?