Can this layout be achieved using only css?

Hi, I have a simple grid layout with a header, main content, and footer. Occasionally, the main content includes a blog post, and I’d like to have a table of contents appear in an aside to the right of the blog post on desktop PCs. However, on mobile devices, I want the table of contents to appear below the blog post title. How can I achieve this with CSS and HTML? I want the aside area to switch between two positions: once appearing as a sidebar and once being part of the main content.

The page looks like this:

<body>
  <div class="grid-container">
    <header>
      Header
    </header>

    <main class="main">
      <div class="blog-container">
        <div class="blog-post">
          <h2>Title</h2>
          <p>Lorem ipsum dolor sit..</p>
        </div>
      </div>
    </main>

    <footer class="footer">
      Footer
    </footer>
  </div>
</body>

The mobile first CSS:

.grid-container {
  display: grid;
  grid-gap: 10px;
  grid-template-areas:
    "header"
    "main"
    "footer"
}

The desktop CSS:

@media (min-width: 52em) {
  .grid-container {
    grid-template-columns: minmax(300px, 800px);
    justify-content: center;
  }
}

I’m curious if it’s possible to achieve what I want using only CSS and media queries. Any suggestions appreciated.

This is just my first thought and may be a bit rough around the edges and over-cooked. The with-toc class is added to the grid container when you want the toc element to show. It uses a bit of a magic number to hold the space open so that the element can be moved with margins.

Generally with grid you need everything to be siblings if you want them to occupy certain areas and to be able to move around. Of course that makes styling very difficult as you have no containers to style.

Its getting late here so I may have missed the obvious solution :slight_smile:

1 Like

Thank you very much for your time. I really appreciate it. This forum is incredible.

2 Likes

Duplicate the ‘table’ of contents and simply show one of them according to browser width . . . .

1 Like

I just noticed that I didn’t define areas for the h2 and the p element content. That means that if the TOC stretched down then it stretched the h2 with it.

Here’s a fix for that:

Although I don’t like duplicating content it may be that the solution by @Archibald is a little easier to manage.:slight_smile: