Mar 3, 2016

A horizontal scrolling code box in blogger

To display code in a blog I like to use a "code box" because I think it presents a more "professional" look. But it's not that easy with blogger.

By "code box" I mean a "window" with a monospaced font and vertical and horizontal scrolling bars as necessary. The internet search solutions I found almost worked, but not quite with blogger because the horizontal scroll bar wouldn't show up as expected. The vertical bar was there, but not the horizontal bar. Go figure.

But if you are comfortable hitting the HTML button next to Compose, that's easily fixed.



First of all, vertical scroll bars aren't usually necessary with blogger because by default it stretches your window vertically as much as it takes. But that's exactly why you need scroll bars, because you don't want a long program to hijack the real estate of your blog. So you need to specify a height.

Since I'm specifying the height, I might as well shrink the width too, a bit radically to more easily display the point. And let's start off with a default-ugly border so we can more easily see the window.

Here is a some HTML that should repeat a Mother Goose rhyme in a monospace-fonted window with as-necessary scroll bars:

<div style="border: solid; height: 1in; width: 50%; font-family:courier; overflow: auto;">
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
</div>

And here is what the window looks like. See the problem?

Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.

The lines wrap when they should have stayed extended, and a horizontal scroll bar should have shown up because I said, quite clearly, "overflow: auto;". So how do I get horizontal scrolling with blogger?

Here's the trick: add "white-space:nowrap;" Wow. Didn't see that coming.

Here is the code box's final opening opening div:

<div style="border: solid; height: 1in; width: 50%; font-family:courier; overflow: auto; white-space:nowrap;">

and here is the resulting window:

Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.
Peter Piper picked a peck of pickled peppers.

Works for me.

3 comments:

  1. PS: If you're using an OS X (Yosemite here) trackpad, the scroll bars don't show until the OS decides you need them. Click in a window and when you scroll on the trackpad, the bars will show.

    ReplyDelete