我可能在这里遗漏了一些非常简单的东西,但请耐心等待。
我想要的是一个 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 垂直居中而不使其扩展以填充其内容?
最佳答案
我想我已经自己解决了。这适用于 Google Chrome - 我尚未在其他浏览器中进行测试。
技巧是使用标准的table-cell
方法,并将vertical-align
设置为middle
。为了阻止表格扩展以填充其内容,我使用table-layout:fixed
。看来有效。
示例代码:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<style>
.wrapper {
background-color: #CCC;
display: table;
table-layout: fixed;
width: 100%;
height: 500px; /* For example. */
}
.container {
background-color: #DDD;
display: table-cell;
vertical-align: middle;
}
.content {
background-color: #EEE;
white-space: nowrap;
overflow: auto;
}
</style>
</head>
<body>
<div class="wrapper">
<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>
</div>
</body>
</html>
关于html - 水平滚动 div 的垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4180594/