3

Having this CSS:

.foo { background-size: 10px 20px; }

And this Html:

<span class="foo"></span>

And this C#:

var parser = new HtmlParser();
var doc = parser.Parse("http://localhost/test.html");
var element = doc.QuerySelector("span.foo");

How do I get the associated background width and height to element?

(Currently I'm using AngleSharp version 0.9.9)

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
SamuGG
  • 479
  • 2
  • 8
  • 20

1 Answers1

6

First of all the C# code is wrong. The string you pass on to parser.Parse is an HTML code, not an URI. Also your code does not do any CSS parsing - it is only using an HTML parser. Thus let's use a browsing context to get all you need.

var config = Configuration.Default.WithDefaultLoader().WithCss();
var context = BrowsingContext.New(config);
var document = context.OpenAsync("http://localhost/test.html").Result;
var element = document.QuerySelector("span.foo");
var style = document.DefaultView.GetComputedStyle(element);
var size = style.BackgroundSize;

Keep in mind that element may be null if no such element exists (none matching the query) and that the GetComputedStyle method only works in a limited way. Also if your CSS is defined in an external style sheet make sure to activate resource loading.

Hope this helps!

Florian Rappl
  • 3,041
  • 19
  • 25
  • Thanks, after a minor fix, got your code working. It just needs to add document loading support to the config like this: `var config = Configuration.Default.WithDefaultLoader().WithCss();` otherwise the document body is always empty. – SamuGG Dec 19 '17 at 14:18
  • 1
    Yes indeed (I focused on the CSS part alone - so I skipped everything else from the config). I modified my answer. Thanks for your reminder! – Florian Rappl Dec 19 '17 at 23:02