Установите ширину ячейки таблицы в процентах от предка, не влияя на ширину соседней ячейки

В HTML у меня есть проблема, объясненная в этом примере, которую вы можете увидеть в действии здесь:

<html>
<style>
table, td {border:1pt solid; border-collapse:collapse;}
figure {margin:0pt}
</style>
<body>
<section style="border:1pt solid; width:600px;">
  <p>This &lt;section&gt; has a surrounding border, 
  and has a fixed width of 600px solely for the purpose of the demonstration. 
  In the application I cannot predict what the width of the &lt;section&gt; 
  will be.</p>

  <p>First table with no styling except border. Not what I want because the
  third column is too wide. It is supposed to only be 25% of the ambient 
  &lt;section&gt; (which will of course be a larger percentage of the table
  than 25%).</p>

  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td>
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>

  <p>Second table with its third cell at 25%. Browser takes that to mean 25%
  of the table width. Not what I want because the other cells grow to be too 
  wide.</p>

  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td style="width:25%">
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>

  <p>Third table looks the way I want it to look. The 3rd column has width 25%
  of the section width. However in this example I achieved that by knowing that
  I had set the section width to 600px, and so I manually set that cell's width
  to 150px. In my application I will not be able to predict the width of the
  ambient section. I also want to achieve this result without specifying any
  widths which would require predicting or knowing how wide "Word" will be.</p>

  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td style="width:150px">
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>
</section>

</body>
</html>

Я хотел бы <td> содержащий <p> иметь (указанную встроенную) ширину, которая составляет 25% от <section> ширина, но пусть другой <td>s сохраняют свою естественную ширину (минимальная ширина, чтобы содержать их содержимое).

Если я использую width:25% на этом <td>браузеры (ну, по крайней мере, Firefox 47.0), кажется, находят ширину для этой ячейки, а затем делают <table> в четыре раза больше ширины, а остальные три ячейки имеют такую ​​же ширину, что и ячейка абзаца. Это делает эти три другие клетки слишком широкими.

Есть ли CSS или техника сценариев, которую я могу использовать для достижения того, чего хочу?


Примечание: я не могу предсказать ширину слов. Это все автоматически сгенерированный контент. Поэтому я не могу вручную отрегулировать любой процент, чтобы получить ширину как раз правильно.

2 ответа

Хм, на этот раз я попробовал это с jQuery. Кажется, это проблема, когда вы устанавливаете тд с%. Поэтому я использовал jQuery для вычисления новой ширины на основе ширины фигуры (в пикселях).

Я также добавил класс.figure к последней таблице, чтобы он применялся только там. Я предполагаю, что вы сможете найти конкретную таблицу на основе селектора CSS.

Если вы хотите применить то же самое к нескольким различным таблицам, используйте функцию цикла. Но для простоты я не буду этого делать в этом примере. https://jsfiddle.net/qLyjj9sd/2/

HTML

<body>
<section style="border:1pt solid; width:600px;">
  <p>This &lt;section&gt; has a surrounding border, 
  and has a fixed width of 600px solely for the purpose of the demonstration. 
  In the application I cannot predict what the width of the &lt;section&gt; 
  will be.</p>

  <p>First table with no styling except border. Not what I want because the
  third column is too wide. It is supposed to only be 25% of the ambient 
  &lt;section&gt; (which will of course be a larger percentage of the table
  than 25%).</p>

  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td>
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>

  <p>Second table with its third cell at 25%. Browser takes that to mean 25%
  of the table width. Not what I want because the other cells grow to be too 
  wide.</p>

  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td>
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>

  <p>Third table looks the way I want it to look. The 3rd column has width 25%
  of the section width. However in this example I achieved that by knowing that
  I had set the section width to 600px, and so I manually set that cell's width
  to 150px. In my application I will not be able to predict the width of the
  ambient section. I also want to achieve this result without specifying any
  widths which would require predicting or knowing how wide "Word" will be.</p>

  <figure class="figure">
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td>
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>
</section>

</body>

CSS

table, td {border:1pt solid; border-collapse:collapse;}

figure {margin:0pt}

Javascript -> JQuery

$(document).ready(function(){
    var newWidth = $(".figure").width() * 0.25;
  $(".figure td:nth(2)").width(newWidth);
});

Пример: https://jsfiddle.net/2uokvrtn/

Ты пробовал:

HTML

<html>
<body>
<section>
  <figure>
    <table>
      <tbody>
        <tr>
          <td>Word</td>
          <td>Word</td>
          <td>
            <p>Paragraph with many many many many words.</p>
          </td>
          <td>Word</td>
        </tr>
      </tbody>
    </table>
  </figure>
</section>
</body>
</html>

CSS

td:first-child{
   width: 25%;
   border: 1px solid red;
}
table{
  width: 100%;
}
Другие вопросы по тегам