ScreenshotNeo

BlogHow-to

How to Load CSS from a String in Go

Parse CSS held in a Go string with a reader adapter or a direct string API. Learn how to choose a parser, handle errors, and tell parsing apart from browser rendering.

By the ScreenshotNeo team30 September 20269 min read

How to Load CSS from a String in Go

If your CSS is already in a Go string, pass it to a reader-based API with strings.NewReader(cssText) or bytes.NewBufferString(cssText). You do not need to write it to a temporary file. If you want a library that accepts a string directly, github.com/aymerick/douceur/parser documents parser.Parse(cssText). Choose based on what you need next: token and grammar iteration, a stylesheet representation, HTML inlining, or actual browser rendering are different tasks.

1. Choose the operation before the library

“Load CSS” can refer to several operations. A parser reads CSS syntax and exposes tokens, grammar units, or a stylesheet representation. Parsing does not apply the declarations to a browser DOM, and it does not automatically retrieve stylesheets referenced by a page with <link rel="stylesheet">.

What you need Approach What it does not imply
Parse a full stylesheet or inspect grammar Use a CSS parser such as github.com/tdewolff/parse/v2/css with an io.Reader. It does not render a page or fetch external assets.
Parse a string into a stylesheet value Use an API that accepts a string, such as documented douceur/parser.Parse. Parsing alone does not inline rules into HTML.
Move rules into HTML style attributes Use an HTML inliner, such as Douceur’s inliner for CSS defined in the HTML document. Douceur’s inliner does not fetch linked external stylesheets.
See how CSS affects a rendered page Load the page and CSS in a browser or browser automation environment. A Go parser is not a browser engine.

Use reader adaptation when the selected API expects a reader. Use a direct string API when it is available and its output matches your task. For inline declarations such as color: red in a style attribute, check whether the parser has a mode for declarations rather than a complete stylesheet.

2. Load CSS into a reader-based parser

The standard library provides an in-memory io.Reader adapter. strings.NewReader is convenient for a Go string. bytes.NewBufferString is another documented pattern; both avoid disk I/O. The tdewolff parser documentation demonstrates wrapping CSS text with bytes.NewBufferString, passing it to parse.NewInput, and constructing a CSS parser.

A Go string can be adapted to the reader interface a CSS parser expects, entirely in memory.
A Go string can be adapted to the reader interface a CSS parser expects, entirely in memory.

Runnable example with tdewolff/parse

Create a module and add the parser dependency using the version selected for your project. The import paths below are the package paths documented for the v2 parser. Review the package’s current version and API before pinning it.

mkdir css-from-string
cd css-from-string
go mod init example.com/css-from-string
go get github.com/tdewolff/parse/v2

Save this as main.go. The example loops until the parser reports its stop grammar, then checks the parser error. It reports grammar units rather than trying to interpret or rewrite CSS.

package main

import (
    "fmt"
    "io"
    "strings"

    "github.com/tdewolff/parse/v2"
    "github.com/tdewolff/parse/v2/css"
)

func main() {
    cssText := `body {
  color: rebeccapurple;
  margin: 0;
}`

    input := parse.NewInput(strings.NewReader(cssText))
    parser := css.NewParser(input, false) // false means a stylesheet, not style-attribute contents

    for {
        grammar, _, data := parser.Next()
        if grammar == css.ErrorGrammar {
            break
        }
        fmt.Printf("grammar=%v data=%q values=%q\n", grammar, data, parser.Values())
    }

    if err := parser.Err(); err != nil && err != io.EOF {
        panic(err)
    }
}

Run it with go run .. The parser’s API exposes Next(), Values(), and Err(); the exact meaning of each grammar value depends on the parser’s grammar model. Build your own transformation on the documented structures rather than treating the returned bytes as a browser’s computed style.

The second constructor argument is an input-context flag. Set it to false for a complete stylesheet, as above. For declarations from a style attribute, use the inline mode documented by the package. Feeding declaration fragments as if they were full rules can produce confusing parse behavior.

Using bytes.NewBufferString

If you are following the package documentation’s form, replace strings.NewReader(cssText) with bytes.NewBufferString(cssText) and import bytes. Both provide reader input. Prefer the adapter that makes the expected input clear in your code. There is no need to copy the string to a file just to satisfy a reader-oriented API.

3. Parse a string directly with Douceur

If you need a parsed stylesheet and prefer a direct string call, Douceur documents parser.Parse(input). The following small program shows the API shape and prints the resulting stylesheet representation.

mkdir css-with-douceur
cd css-with-douceur
go mod init example.com/css-with-douceur
go get github.com/aymerick/douceur
package main

import (
    "fmt"
    "log"

    "github.com/aymerick/douceur/parser"
)

func main() {
    cssText := `h1 { color: steelblue; }
.note { padding: 0.5rem; }`

    stylesheet, err := parser.Parse(cssText)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(stylesheet.String())
}

Run with go run .. This is a direct string interface, so a reader adapter is unnecessary for this call. Before adopting any dependency, check the version, supported CSS features, compatibility with your Go version, and current maintenance. The research sources establish the documented APIs, not a complete present-day maintenance comparison or benchmark.

4. Handle inline declarations and full stylesheets correctly

A stylesheet generally contains rules, selectors, and declaration blocks, for example .card { color: navy; }. Inline style content is a declaration list, such as color: navy; margin: 0, without a selector and outer braces. APIs may parse these contexts differently. For tdewolff, the documented parser takes an isInline flag; set it according to the actual input context.

Full stylesheet input and style-attribute declarations have different shapes and may need different parser modes.
Full stylesheet input and style-attribute declarations have different shapes and may need different parser modes.
  • For a complete CSS file held in a string, use stylesheet mode.
  • For the contents of an HTML style attribute, use inline/declaration mode if the parser supports it.
  • Do not wrap a declaration fragment in an invented selector unless the downstream operation expects a complete rule.
  • Keep the original string if you need to preserve exact formatting; parser output may represent structure rather than byte-for-byte source.

CSS parsing and HTML inlining are also separate. Douceur provides an inliner for CSS defined within an HTML document. Its README states that the inliner does not fetch external stylesheets, so retrieve and provide those resources through the appropriate part of your application if they are needed.

5. Read CSS from other sources into a string or reader

If the CSS starts in a file, network response, or generated template, you can still use the same parser interface. For a string already in memory, use a reader adapter. For a file or response body, pass a reader directly when the parser API accepts one, and close resources according to their ownership rules.

// In-memory text:
reader := strings.NewReader(cssText)

// File input (handle the error and close file in real code):
file, err := os.Open("site.css")
if err != nil {
    return err
}
defer file.Close()
input := parse.NewInput(file)

The file snippet is a pattern for connecting a reader source; it belongs inside a function that returns an error and needs os in its imports. Avoid reading a large file into a string unless you need string operations or the selected API only accepts strings. Conversely, do not add buffering and file conversion for a small in-memory string unless another part of your program needs that representation.

6. Errors, malformed input, and edge cases

Do not assume that reaching the parser’s stop condition means every operation succeeded. Follow the package’s documented end-of-input and error conventions. In the tdewolff example, ErrorGrammar ends iteration and Err() lets the caller inspect the terminal error. Treat normal end-of-input as completion; return or report other errors.

Symptom Likely cause What to check
Code does not compile after copying an example The installed package version differs from the documented API, or imports are missing. Check the module version and package docs; ensure parse and css imports match the selected v2 API.
Parser stops sooner than expected The input is malformed, truncated, or being fed in the wrong context. Check Err(), inspect the source around the stop, and verify stylesheet versus inline mode.
Declarations do not form rules Declaration-list text was parsed as a full stylesheet, or vice versa. Use the correct input mode and supply the grammar shape the operation expects.
Styles from a linked file are absent The parser only received the CSS string; it did not fetch a URL. Fetch the resource separately or use a browser environment that loads the page and its dependencies.
HTML still has class-based rules after inlining The rules were in a separate external stylesheet, outside the inliner’s documented input scope. Provide CSS in the supported HTML context or handle external stylesheet retrieval yourself.
Output differs in whitespace or formatting The parser’s serializer formats a representation instead of preserving original bytes. Keep the source string when exact textual preservation matters; compare semantic output for transformations.
Special CSS values are not understood downstream The chosen parser or consumer may not support a syntax feature or may expose tokens at a lower level. Confirm feature support for your dependency version and test representative input from your use case.
Unexpected behavior with empty input An empty string contains no stylesheet rules and may immediately reach end-of-input. Handle empty CSS as a valid no-op only if that matches the surrounding application’s contract.

For untrusted input, keep resource use bounded at the application boundary: set an acceptable maximum input size before parsing, and avoid treating arbitrary CSS as safe HTML or safe browser content. A parser’s successful syntax handling is not a security policy. If you later embed values into HTML, use context-appropriate escaping and a deliberate sanitization policy.

7. Performance, reliability, and cost

Adapting a string to a reader is an in-memory step; it does not involve a temporary file. The research provides no benchmarks comparing strings.NewReader, bytes.NewBufferString, or the candidate parsers, so do not infer a speed advantage from the API shape. Measure with your actual CSS sizes and transformations if latency or allocation behavior matters.

For repeated parsing, decide whether to parse once and reuse an immutable representation or parse per request based on your application’s correctness requirements. Do not share mutable parser state across concurrent goroutines unless the chosen package documents that as safe. Handle errors at the boundary so one malformed stylesheet does not silently become a successful empty result.

The Go parsing path has no ScreenshotNeo usage cost. If the actual goal is to capture a rendered page rather than inspect CSS syntax, a browser screenshot service solves a different problem. ScreenshotNeo is a website screenshot API and MCP server from Yorker Media; its API accepts one GET request with a URL and returns a PNG, JPEG, WebP, or PDF. See the ScreenshotNeo site for the product overview.

Or skip the browser setup

For a rendered-page screenshot, call the ScreenshotNeo API instead of wiring up a browser. See the ScreenshotNeo API documentation for the API details and available options.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));

ScreenshotNeo accepts cookie and consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, with response headers identifying the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf for Claude, Cursor, and other MCP clients. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots.

Sign up for ScreenshotNeo’s free 1,000 screenshots a month, with no card.

8. Frequently asked questions

Do I need to save the string to a temporary CSS file?

No. If the parser accepts an io.Reader, wrap the string with strings.NewReader or bytes.NewBufferString.

Does parsing CSS apply the styles to HTML?

No. Parsing interprets CSS syntax. Applying it requires a browser or another style-processing system. An HTML inliner performs a separate rewrite operation.

Will Douceur fetch a linked stylesheet for me?

No. Its documented inliner handles CSS defined in the HTML document and does not fetch external stylesheets.

Which parser is fastest?

The available research does not establish a comparative benchmark. Choose by input shape and output needs, then benchmark representative workloads if speed matters.

Can I use this for CSS in a screenshot workflow?

Use a parser when you need to inspect or transform CSS. Use a browser capture workflow when you need the rendered page as an image or PDF; ScreenshotNeo’s API and MCP server support that separate task.