I’m probably missing something very simple here, but please bear with me.
What I want is a div, filling 100% of the width of its parent div (and no more), vertically centered within its parent div, containing content which should horizontally scroll rather than wrapping. Both the inner div and the parent div have variable heights.
I’ve managed to get the inner div to scroll its content without wrapping by applying this CSS to it:
.content {
white-space: nowrap;
overflow: auto;
}
I attempted to center this vertically within its parent div with the following CSS:
.container {
height: 500px; /* For testing purposes. */
display: table-cell;
vertical-align: middle;
}
But as soon as I do this, the inner div stops obeying the overflow: auto rule, and it expands to fill its contents. Try it yourself with and without the display: table-cell line and watch what happens:
<!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>
How can I get the div to vertically center without making it expand to fill its contents?
I think I’ve worked it out for myself. This works in Google Chrome – I have yet to test it in other browsers.
The trick is to use the standard
table-cellmethod withvertical-alignset tomiddle. In order to stop the table from expanding to fill its contents, I usetable-layout: fixed. It seems to work.Example code: