DEV Community

Cover image for CSS Hack: Let Code Blocks Break Free From Container Width
CodeCadim by Brahim Hamdouni
CodeCadim by Brahim Hamdouni

Posted on • Originally published at barim.us

CSS Hack: Let Code Blocks Break Free From Container Width

Text prose and code have fundamentally different width requirements.

Prose benefits from restricted width because lines of 50-75 characters are the fastest to read, reduce eye strain and movement, and let you track easily from line end to next line start.

But code blocks suffer from width restrictions. They force horizontal scrolling for long lines, break code structure and indentation, hide relationships in function calls and data structures, and make copying and understanding difficult.

Here is an example of one of my previous articles with my old Hugo style:
Example of text correctly wrapped but the code block is cut on the right
I need to horizontally scroll to read the rest of the parameters passed to the load_extension function.

The Solution

Use Hugo's wrapperClass and CSS negative margin to let code blocks extend beyond text width while keeping prose properly wrapped.

Step 1: Configure Hugo

Add a CSS class to all code blocks in your config.yaml:

markup:
  highlight:
    wrapperclass: highlight full-width-content
Enter fullscreen mode Exit fullscreen mode

Step 2: Add the CSS Magic

The CSS uses negative margin to break out of the parent container:

.full-width-content {
    margin-right: -50vw;
    max-width: fit-content;
    position: relative;
}
Enter fullscreen mode Exit fullscreen mode

How it works: The -50vw (50% of viewport width) assumes your content is roughly centered and we target only the right margin because we want to stay left aligned and expand on the right. The fit-content ensures the code block only expands as needed, and position: relative keeps it in the document flow.

The Result

The result on the same content with text also wrapped but code block expands as necessary

Perfect! Text stays readable while code gets the space it needs.

Considerations

  • fit-content is supported in all modern browsers
  • On very narrow screens, you might want to add a media query to disable this behavior
  • Ensure your main content is centered for the -50vw trick to work effectively

References

Top comments (0)