Change aspect ratio of 3 column displays: table / table-cell

I have this simple setup:

.container {
  display: table;
  width: 70%;
  text-align: center;
}
div {
  border: 1px solid #336;
}
.column {
  display: table-cell;
}
      

<div class="container">
  <div class="column">Column 1.</div>
  <div class="column">Column 2 is a bit longer.</div>
  <div class="column">Column 3.</div>
</div>
      

Run codeHide result


jsFiddle: http://jsfiddle.net/aqk1yy1d/

This table cell behavior expands as the window resizes. I would like the center cell / div to be anchored to its content and not expand. Basically the sides should expand, but not the inner cell, which should be sized.

I can't see how to do this without setting a specific width somewhere, but that's not okay because I will have different content lengths in that middle cell ....

Any pointers?

+3


source to share


2 answers


The trick is to set both the left and right columns to 50% of the table width. The center column is 1px wide. If there is content larger than 1px in the center column, this will cause the center column to grow.

The first example contains only text inside it, which will be completed at the first moment. To reduce this, add something like white-space: nowrap

to keep all text on one line, or to make sure you have content with 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>
      

Run codeHide result


+3


source


If you can't find a better solution, you can try using javascript to dynamically set the width. 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>

      

javascript will look like this:



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

      

You would call this on $(document).ready()

or whenever the content changes. You should of course also remove the border from the inner column so that you can't point the nested div to it

0


source







All Articles