Better Blog Format: Keep Your Context In Sight
Better Blog Format: Keep Your Context In Sight
29/09/2019
CSS

Better Blog Format: Keep Your Context In Sight

If you are a designer or developer and consume a lot of blog content, you may have experienced this issue, a big chunck of prose followed by a large image or a block of code. Quite often, both will not fit on the screen at the same time, requiring you to scrolling back and forth to remember the context.

Apple recently released some amazing interactive tutorials to accompany their new SwiftUI framework. The tutorials feature two columns, one containing scrollable boxes with explanation of the code and changes, and the other with the code itself, sometimes with a rendering of the work in progress app.

Apple SwiftUI Tutorial GIF

The magic occurs in the second column which "sticks" to the top of the page as the content, which references it, scrolls by. The solution turns out to be exceptionally easy but makes an enourmous impact.

The effect works best at desktop screen sizes. You can try removing all padding and margins to squeeze two columns onto a phone display, but I've gone with a single column fallback for this page on mobile.

The sections are wrapped in a container div which we can target in CSS. Making this container display: flex will give us columns. These can be sized to best accommodate the content.
The 'content' section will be a normal paragraph element with no additional styles. This will need to be larger than the sticky content in order to trigger the effect, we'll throw a chunck of Lorem Ipsum into the final result to achieve this.
The second element will recieve position: sticky. This will cause its contents to stick to the view until the rest of the elements in the container have scrolled passed.
We will also need to designate how the element will stick to the containing div. Here I have gone for 'top' to emulate the effect from the Apple tutorials.
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Sticky Sections!</title>
</head>
<body>
    <div class="container">
        <p>This section will scroll by as usual</p>
        <aside class="sticky">
            This section will stick
        </aside>
    </div>
</body>
</html>

Here is the CSS for our example with the bare minimum highlighted.







 
 
 
 




 
 
 
 
p,
aside {
  width: 60vw;
  padding: 2rem;
}

.container {
  display: flex;
  align-items: flex-start;
  margin: 0 auto;
  max-width: 960px;
}

.sticky {
  position: sticky;
  top: 0;
}

Try it out for yourself

Related articles

Find me elsewhere 👉