预标记导致页面在CSS网格中水平滚动

时间:2017-08-02 18:41:00

标签: html css css3 pre css-grid

我正在努力将我的网站切换到CSS Grid。我发现了一个意外的行为。

我有一个简单的CSS-Grid布局标题,跨越两列,下一行的侧面导航具有固定大小,主要内容使用剩余空间。

在main元素中包含带有演示代码的pre标签。前面是一个相当长的行,对于某些屏幕尺寸,它会将主区域推到浏览器视图之外。

我想要的是pre必须水平滚动。

body {
  margin: 40px;
}

pre {
  overflow: auto;
  background-color: #ffffff;
  border: 1px solid #898989;
  padding: 5px;
}

header {
  background: #e1e1e1;
  grid-area: header;
}

aside {
  grid-area: aside;
  background: #d7d7d7;
}

aside nav {
  background: #e1e1e1;
}

aside nav ul {
  list-style: none;
  padding-top: 10px;
}

aside nav ul li {
  margin-bottom: 10px;
}

main {
  background: #c2c2c2;
  grid-area: main;
}

.box {
  border-radius: 5px;
  padding: 20px;
}

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-areas: "header header" "aside main";
  grid-template-columns: 200px 1fr;
  grid-template-rows: 110px 1fr;
}
<div class="grid">
  <header class="box">
    <h1>Site Name and Navigation Bar</h1>
  </header>
  <aside class="box">
    <h1>Sidebar</h1>
    <p>This is the sidebar. Might have secondary navigation elements.</p>

    <nav>
      <ul>
        <li><a href="">Link to nowhere</a></li>
        <li><a href="">Link to nowhere</a></li>
      </ul>
    </nav>
  </aside>
  <main class="box">
    <h1>Main Content</h1>
    <p>The following <code>pre</code> element will be too large for our grid. It will not have a horizontal scrollbar if it has lines that exceed its width.</p>
    <h2>Darn Pre</h2>
    <pre><code>&lt;html&gt;
  &lt;body&gt;
    &lt;p&gt;I like long sentences and can not lie. Look at it it's so big. That make your page to be far to wide. I want to get horizontal with the freaky line. My homeboys tried to warn me that pre can make you layout funky. 
    &lt;/p&gt;
  &lt;/body&gt;
&lt;/html&gt;
      </code></pre>
    <main>
</div>

codepen with demo of this problem

1 个答案:

答案 0 :(得分:1)

Pre标签会尝试填充所有可用空间。修复是以某种方式限制它。

我通过添加另一个1fr列并具有主跨度来修复此问题。

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-areas: "header header header" "aside main main";
  grid-template-columns: 200px 1fr 1fr;
  grid-template-rows: 110px 1fr;
}

Codepen example showing my fix