我可能在这里遗漏了一些非常简单的东西,但请耐心等待。
我想要的是一个div,填充其父div的宽度的100%(并且不再),在其父div中垂直居中,包含应该水平滚动而不是包裹的内容。内部div和父div都有可变的高度。
我设法让内部div通过将CSS应用到它来滚动其内容而不进行包装:
.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垂直居中而不扩展以填充其内容?
答案 0 :(得分:2)
我想我已经为自己解决了这个问题。这适用于谷歌浏览器 - 我还没有在其他浏览器中测试它。
诀窍是使用标准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>
答案 1 :(得分:1)
您需要使用不同的垂直居中技术,因为制作display:table-cell
内容使其显示为table tr td
,这意味着您正在观察的行为是正确的,因为表格单元格扩展为适合内容,没有溢出。 (哇,这是一个长句)
尝试使用绝对定位负边距tecnique:
#parent { position:relative; }
#content { position:absolute; top:50%; margin-top:-50%; }
css没有经过测试,不在我的脑海中,但这就是它的工作原理。