Home >Web Front-end >CSS Tutorial >Should I Embed CSS Inline or Reference a CSS File from Assets for Styling HTML in a WebView?
Question:
In an app using JSoup to parse HTML for a mobile WebView, it's desirable to strip unwanted elements and apply custom styling via CSS. The question is, is it better to embed CSS inline within the HTML or reference a CSS file from assets?
Answer:
Referencing a CSS file from assets is the preferred method for styling HTML in a WebView.
Solution:
To use a CSS file from assets:
// Assume "/assets/style.css" is the CSS file in the assets directory String htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />"; webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
This approach allows you to easily update the CSS without modifying the HTML, and ensures that the CSS is loaded and applied after the HTML has been parsed.
Alternative (Inlining CSS):
While it's possible to inject CSS into the HTML as you process it, this method is less desirable as it requires additional processing logic and can be prone to errors.
The above is the detailed content of Should I Embed CSS Inline or Reference a CSS File from Assets for Styling HTML in a WebView?. For more information, please follow other related articles on the PHP Chinese website!