html – 表单元格在包含可滚动的pre时没有正确调整大小

我无法让我的表格单元格在“圣杯”布局的变体上正确调整大小.

当我的主要内容显示为块与表格单元格时,我会看到不同的行为.我已经将问题缩小到这样一个事实,即具有长文本的可滚动预块导致单元格宽度表现奇怪.请参阅下面的代码和小提琴.它显示了什么与期望的行为不一致.

请注意display:table-cell是必需的.我不能简单地使用样式作为工作示例(我也不能使用flexbox).

重要:
要查看所需的调整大小行为,您必须调整窗口大小并观察两个示例的行为方式.确保您在代码段结果上单击“完整页面”才能执行此操作.

#main {
  display: table;
  margin: 0 auto;
}

#content {
  display: table-cell;
  max-width: 600px;
  background-color: red;
}

.code-block {
  /* display: none; */
  margin: 0px 20px;
  padding: 10px;
  border: 1px black solid;
  overflow: auto;
}

#content-working {
  display: block;
  margin: 0 auto;
  max-width: 600px;
  background-color: green;
}
<div id="main">
  <div id="content">
    <h1>
      Content Area
    </h1> Some other words on the page. Hey look, some code:
    <pre class="code-block"><code>code that is potentially long and must be scrolled to be seen in its entirety</code></pre>
  </div>
</div>

<!-- desired behavior below -->

<div id="main-working">
  <div id="content-working">
    <h1>
      Content Area
    </h1> Some other words on the page. Hey look, some code:
    <pre class="code-block"><code>code that is potentially long and must be scrolled to be seen in its entirety</code></pre>
  </div>
</div>

要查看代码块是问题,您可以取消注释/ * display:none; * /并看到内容列正确调整大小(尽管没有所需的代码块).

最佳答案 您可以通过添加table-layout简单地解决问题:fixed;宽度:600%;你的#main风格.另外,要应用max-width,我们可以在主div(名为#mainContainer)周围添加一个包装器.

结果如下面的代码段:

#mainContainer {
  max-width: 600px; 
  margin: 0 auto; /* make center */
}

#main {
  display: table;
  margin: 0 auto;
  table-layout: fixed;
  width: 100%; /* without this, table-layout:fixed not work! */
}

#content {
  display: table-cell;
  /*max-width: 600px; set in parent div */
  background-color: red;
}

.code-block {
  /* display: none; */
  margin: 0px 20px;
  padding: 10px;
  border: 1px black solid;
  overflow: auto;
}

#content-working {
  display: block;
  margin: 0 auto;
  max-width: 600px;
  background-color: green;
}
<div id="mainContainer">
 <div id="main">
  <div id="content">
    <h1>
      Content Area
    </h1> Some other words on the page. Hey look, some code:
    <pre class="code-block"><code>code that is potentially long and must be scrolled to be seen in its entirety</code></pre>
  </div>
 </div>
</div>

<!-- desired behavior below -->

<div id="main-working">
  <div id="content-working">
    <h1>
      Content Area
    </h1> Some other words on the page. Hey look, some code:
    <pre class="code-block"><code>code that is potentially long and must be scrolled to be seen in its entirety</code></pre>
  </div>
</div>
点赞