Skip to content Skip to sidebar Skip to footer

Change Proportions Of 3 Columned Display: Table / Table-cell

I have this simple setup: jsFiddle: http://jsfiddle.net/aqk1yy1d/ This table-cell behavior expands with window resize. I would like the center cell/div to be fixed to its content

Solution 1:

The trick is to set both the left and right column to take up 50% of the width of the table. The center column gets a width of 1px. If there is content larger than 1px in the center column it will force the center column to grow.

The first example only has text inside it, which will wrap at the first moment. To mitigate this add something like white-space: nowrap to keep all text on a single line or make sure that you have content with a width.

.container {
  display: table;
  width: 70%;
  text-align: center;
  margin-bottom: 10px;
}
div {
  border: 1px solid #336;
}
.column {
  display: table-cell;
}
.left,
.right {
  width: 50%;
}
.center {
  width: 1px;
}
.center-content {
  white-space: nowrap;
}
<div class="container">
  <div class="column left">Column 1.</div>
  <div class="column center">Column 2 is a bit longer.</div>
  <div class="column right">Column 3.</div>
</div>

<div class="container">
  <div class="column left">Column 1.</div>
  <div class="column center"><div class="center-content">Column 2 is a bit longer.</div></div>
  <div class="column right">Column 3.</div>
</div>

Solution 2:

If you can't find a better solution, you could try using javascript to set the width dynamically. Change your html to something like this:

<div class="container">
    <div class="column">Column 1.</div>
    <div id="column2Outer" class="column">
        <div id="column2Inner" style="display: inline-block">Column 2 is a bit longer.</div>
    </div>
    <div class="column">Column 3.</div>
</div>

The javascript would be as follows:

$("#column2Outer").css("width", document.getElementById("column2Inner").clientWidth);

You would call this on $(document).ready() or whenever the content changes. You would of course also have to remove the border from the inner column so you can't tell it's a nested div


Post a Comment for "Change Proportions Of 3 Columned Display: Table / Table-cell"