【发布时间】:2012-02-25 01:12:16
【问题描述】:
我可能在这里遗漏了一些非常简单的东西,但请多多包涵。
我想要的是一个 div,填充其父 div 宽度的 100%(仅此而已),在其父 div 中垂直居中,包含应该水平滚动而不是换行的内容。内部 div 和父 div 的高度都是可变的。
通过应用这个 CSS,我设法让内部 div 滚动其内容而不进行换行:
.content {
white-space: nowrap;
overflow: auto;
}
我尝试使用以下 CSS 在其父 div 中垂直居中:
.container {
height: 500px; /* For testing purposes. */
display: table-cell;
vertical-align: middle;
}
但只要我这样做,内部 div 就会停止遵守overflow: auto 规则,它会扩展以填充其内容。在有和没有 display: table-cell 行的情况下自己尝试一下,看看会发生什么:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
.container {
background-color: #DDD;
height: 500px;
display: table-cell;
vertical-align: middle;
}
.content {
background-color: #EEE;
white-space: nowrap;
overflow: auto;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<p>This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test. This is a test.</p>
</div>
</div>
</body>
</html>
如何让 div 垂直居中而不使其扩展以填充其内容?
【问题讨论】: