Today on Hacker News, a link to a repository popped up with the intriguing title,
"CSS in GitHub Readmes"
The repository contains some interesting code and explanation.
Setting it up
In your repository, add a new SVG file with whatever name you like, such as header.svg
.
Then, embed the image in your README using some plain ol' HTML:
<img src="header.svg" width="800" height="400">
Adding your CSS
The following template is all you need to get started. Add this code to your SVG file:
<svg fill="none" viewBox="0 0 800 400" width="800" height="400" xmlns="http://www.w3.org/2000/svg">
<foreignObject width="100%" height="100%">
<div xmlns="http://www.w3.org/1999/xhtml">
<span class="nt"><style></span>
<span class="c">/* your CSS */</span>
<span class="nt"></style></span>
<span class="c"><!-- your HTML --></span>
<span class="nt"></div></span>
</foreignObject>
</svg>
How does this work?
According to the repo,
You can put HTML (actually XHTML) and CSS inside a <foreignObject> tag inside a SVG file inside an <img> tag inside your readme. π€―
The <foreignObject>
tag is a valid SVG element that can contain any form of XML data. The XML data type (namespace) is specified using the inner tag's xmlns
attribute. In this case, we'll use the XHTML namespace:
<div xmlns="http://www.w3.org/1999/xhtml">
Now all of the code inside this <div>
will be rendered as XHTML!
Take extra care when writing XHTML markup. The browser forces much more strict rules than regular HTML, and you might notice some issues that the browser would typically ignore for non-XHTML markup.
What about JavaScript?
GitHub has very specific content loading policies on their servers, and when loading any type of asset the server first sanitizes the data to ensure no foreign JavaScript executes in the browser. Trying to embed <script>
tags or using inline onclick
attributes results in content policy errors in your browser.
Why can't I interact with the SVG's contents?
When rendering the SVG, GitHub loads it inside an <img>
tag that removes the interactivity from the SVG. However, any animations are still rendered in the image.
Hope you enjoyed this fun experiment!
Check out what I did with it here.
Let's develop a website that fits you. Don't settle for a template.
Visit my portfolio to see what I'm about.
Top comments (0)