Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

“Load CSS from a string” can mean three different operations in C#: parse a stylesheet string into CSS rules, parse an HTML string that contains a <style> element, or add CSS to a document for style-service processing. Use AngleSharp for the HTML/DOM route and its companion AngleSharp.Css package for CSSOM-style stylesheet parsing. Html Agility Pack’s LoadHtml handles HTML strings, not a documented CSS stylesheet parser.

Choose the operation before choosing an API

What you have What you need Appropriate route
A CSS string such as body { color: red; } Rules, declarations, selectors, or a CSSOM AngleSharp.Css and its CSS parser
An HTML string containing a <style> element An HTML document and DOM AngleSharp OpenAsync or ParseDocument
An HTML string for scraping Elements, attributes, XPath, or text Html Agility Pack LoadHtml or AngleSharp
Markup that must be laid out and rendered as pixels A browser screenshot or PDF A browser engine or a screenshot service, not just a parser

Parsing CSS and rendering a page are separate jobs. AngleSharp’s documented examples provide DOM and styling services; they do not promise complete browser layout or pixel rendering.

Load HTML containing CSS with AngleSharp

This is the most common interpretation when a program receives a complete HTML fragment or page as a string. Put the stylesheet in a <style> element, create a browsing context, and pass the string as request content.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using AngleSharp;
using AngleSharp.Dom;

string html = @"<!doctype html>
<html>
  <head>
    <style>
      body { color: #222; }
      .notice { font-weight: bold; }
    </style>
  </head>
  <body><p class='notice'>Hello</p></body>
</html>";

IBrowsingContext context = BrowsingContext.New(Configuration.Default);
IDocument document = await context.OpenAsync(req => req.Content(html));

IElement paragraph = document.QuerySelector(".notice");
Console.WriteLine(paragraph?.TextContent);

The important detail is req.Content(html): the string is supplied as the response body rather than fetched from a URL. AngleSharp’s basics documentation also shows direct document parsing:

using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Parser;

var parser = new HtmlParser();
IDocument document = parser.ParseDocument(html);

Use the first form when you want a browsing context and configured services; use ParseDocument for straightforward HTML-to-DOM parsing.

Enable AngleSharp’s CSS services

When you need style processing in the document, add the companion CSS package and enable the CSS service in the configuration. The official example uses:

using AngleSharp;

var configuration = Configuration.Default
    .WithJs()
    .WithCss();

var context = BrowsingContext.New(configuration);
var document = await context.OpenAsync(req => req.Content(html));

WithJs() is only necessary for scripts; retain it when your input requires JavaScript. WithCss() is the relevant extension for stylesheet support. A style element can be supplied in the original HTML, as above, or created through the DOM and appended to the document.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add a style element after parsing

var style = document.CreateElement("style");
style.TextContent = "p { color: navy; }";
document.Head.AppendChild(style);

This inserts CSS text into the document. Whether a particular rule is applied depends on the CSS services and the features supported by the installed package version.

Parse a CSS string into rules (CSSOM)

If your input is only a stylesheet string and you need rule objects rather than an HTML document, use AngleSharp.Css, the companion project for CSS parsing, CSSOM, and styling services. Install a package version compatible with your AngleSharp version; the core repository lists targets including netstandard2.0, net8.0, and net10.0, plus net462 and net472 on Windows. Verify the companion package’s target frameworks separately.

The API reference identifies ICssParser as parsing a stylesheet from a string, and the stylesheet interface exposes rule collections and operations such as Insert(string rule, int index). The API page surfaced for this material is for AngleSharp.Css 1.0.0-alpha-99; do not copy constructor names from an old reference into a newer project without checking the installed package’s IntelliSense or API documentation.

Version-safe workflow

  1. Add AngleSharp and the matching AngleSharp.Css package to the project.
  2. Open the installed package’s API surface and locate the concrete CSS parser or the service that implements ICssParser.
  3. Call its stylesheet-from-string method with your CSS text.
  4. Inspect the returned stylesheet’s rule collection; use the stylesheet insertion method when you need to add a rule.

This approach avoids assuming that an alpha-version constructor still exists. If your application only needs to attach CSS to HTML, the documented <style> plus WithCss() route is simpler and less sensitive to CSS parser API changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Html Agility Pack: useful for HTML, not established as a CSS parser

Html Agility Pack documents HtmlDocument.LoadHtml(html) for loading an HTML string and supports XPath or XSLT-oriented HTML processing. That makes it suitable for extracting a <style> node or inspecting markup:

var document = new HtmlAgilityPack.HtmlDocument();
document.LoadHtml(html);
var styleNode = document.DocumentNode.SelectSingleNode("//style");
string css = styleNode?.InnerText ?? "";

The documented material does not establish Html Agility Pack as a parser that turns a standalone CSS string into CSSOM rules. Use it to read the text, then pass that text to a CSS-capable parser if you need selectors and declarations.

CSS string handling details that prevent bugs

Keep CSS as text, not HTML-encoded text

A C# verbatim string (@"...") is convenient for multiline CSS. If the CSS came from JSON, a database, or an HTML-encoded source, decode or deserialize it before inserting it into a style element. Do not double-encode braces, quotes, or ampersands.

Preserve the stylesheet’s character encoding

If you read bytes from a file or HTTP response, decode them with the correct encoding before passing the resulting string to AngleSharp. A parser cannot recover characters that were already decoded incorrectly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Expect unsupported or invalid CSS to be handled according to the package

Browsers commonly ignore an invalid declaration while retaining other rules. A server-side parser may report errors, omit a rule, or expose it differently. Validate the exact version you deploy, especially for newer CSS syntax, custom properties, and at-rules.

Do not confuse computed style with parsed declarations

A parsed stylesheet tells you what rules were written. A computed value requires a document, the CSS service, selector matching, inheritance, and other browser behavior. If you need the final visual result, use a real browser engine.

When you need an actual screenshot

For pixel output, the DIY path requires a browser setup, navigation, waiting for fonts and lazy content, and handling cookie banners or overlays. A DOM/CSS parser alone does not produce a PNG, JPEG, WebP, or PDF.

Or skip the browser setup:

ScreenshotNeo provides a website screenshot API and MCP server. A single GET request returns an image or PDF, and its capture flow accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before the shot. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response identifies the page verdict and billing result in X-Page-Verdict and X-Billed headers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp

See the ScreenshotNeo documentation for all options, including CSS selectors, custom CSS and JavaScript, waits, device presets, PDF settings, headers, cookies, blocking rules, caching, signed links, asynchronous jobs, bulk capture, and the usage API.

Equivalent Python request

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://example.com"}, timeout=90)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Equivalent Node.js request

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://example.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

The free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Sign up free for ScreenshotNeo.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshooting

“WithCss” is missing

The CSS companion package is not referenced, or its version does not match AngleSharp. Add the matching package and ensure the namespace/imports and target framework are correct.

The style element exists but styles do not appear

Confirm that the document was created with a configuration containing WithCss(), that the CSS is in TextContent, and that you are not expecting pixel rendering from a DOM parser.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The CSS parser API does not match an example

Check the installed package version. The documented ICssParser capability is stable conceptually, but parser construction and concrete method names can vary; use the version’s API reference rather than an alpha-version sample.

Selectors match nothing

Inspect the parsed HTML, ensure the selector is valid, and check that the element is in the same document. CSS in a separate string has no effect until it is attached to a document or parsed through a stylesheet API.

The screenshot contains a popup or bot-check page

A parser cannot dismiss interactive overlays. Use a browser automation flow or ScreenshotNeo’s cleaning and page-verdict features; failed loads and bot checks are not billed by ScreenshotNeo.

Decision checklist

  • Need CSS rules from a CSS-only string? Choose AngleSharp.Css and verify the installed API version.
  • Need a DOM from HTML text? Use OpenAsync(req => req.Content(html)) or ParseDocument.
  • Need CSS applied to that DOM? Include a <style> element and configure WithCss().
  • Need a PNG, WebP, JPEG, or PDF? Use a browser engine or ScreenshotNeo.
  • Need scraping only? Html Agility Pack’s LoadHtml is an HTML parsing route, not a documented standalone CSS parser.

Frequently Asked Questions

Can I use Html Agility Pack to parse a CSS string directly?

Its documented API loads HTML with LoadHtml; the reviewed documentation does not establish a standalone CSS stylesheet parser. Use AngleSharp.Css for CSS rules.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Does AngleSharp render a webpage like Chrome?

The cited examples demonstrate DOM, JavaScript, and CSS services, not complete browser layout or pixel rendering. Use a browser engine for rendered output.

Which AngleSharp.Css version should I install?

Install a version compatible with your AngleSharp version and target framework, then verify the concrete parser API in that installed package. The surfaced API reference is for 1.0.0-alpha-99 and may not be current.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.