DEV Community 👩‍💻👨‍💻

Cover image for Add CSS to your GitHub READMEs
Peyton McGinnis
Peyton McGinnis

Posted on

Add CSS to your GitHub READMEs

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">

      <style>
        /* your CSS */
      </style>

      <!-- your HTML -->

    </div>
  </foreignObject>
</svg>
Enter fullscreen mode Exit fullscreen mode

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.




sergix

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)

Update Your DEV Experience Level:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠