3

I am working on switching my site to CSS Grid. I found an unexpected behavior.

I have a simple CSS-Grid layout header spanning two columns the next row has the side navigation with a fixed size, and the main content using the remaining space.

In the main element contains a pre tag with demo code. That pre is a rather long line, for some screen sizes it pushes the main area outside the browser view.

What I want is for the pre to have to scroll horizontally.

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

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Nicholas Marshall
  • 2,981
  • 2
  • 26
  • 22

1 Answers1

1

A Pre tag will try and fill all available space. The fix is to limit it in some way.

I fixed this by adding another 1fr column and having main span that.

.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

Nicholas Marshall
  • 2,981
  • 2
  • 26
  • 22