Faded codeblocks using CSS
One aspect I’ve gotten stuck on with the styling of this blog is code blocks. I’ve tried adding a border and/or a background color in the past, but I couldn’t stick with either of them and constantly kept changing styles.
I wanted a subtler indication to scroll if a block overflows, and a fading gradient towards seemed like a good option.
Here’s the CSS I wrote for it:
pre {
position: relative;
background: white;
}
pre::after {
content: "";
position: absolute;
top: 0;
bottom: 0;
left: 95%;
right: 0;
background-image: linear-gradient(to right, transparent, white);
}
@media (prefers-color-scheme: dark) {
pre {
background: black;
}
pre::after {
background-image: linear-gradient(to right, transparent, black);
}
}
pre code {
display: block;
padding: 0.75rem 0;
overflow: auto;
padding-inline-end: 1.5rem;
}
The key behind this effect is the ::after
pseudo-element, which is a linear-gradient positioned to the right end of the pre
block. The left
value ensures that the gradient doesn’t overlap the block completely, and acts as a subtle gradient, suggesting the user to scroll to see the code.
Usually I’d add the scroll to the pre
block, however since we want the pseudoelement to stay at a fixed position, the scroll and overflow is applied to the child block - the code
element in this case.
The gradient hiding overflow text makes sense, but this also covers the text at the end of the scroll. This is fixed by adding padding-inline-end
to the code
element, which adds padding at the end of scroll.
Here’s how it looks:
This is a super long string of text that appears to be faded where the text overflows.
While I’ve demonstrated this for codeblocks, this styling could be extended for any block element - say a paragraph within a div, or a paragraph within a blockquote.