400
votes

I have a README.md file for my project underscore-cli, a pretty sweet tool for hacking JSON and JS on the command-line, and I want to document the --color flag.

Currently, the ONLY way to do this is with a screenshot (which can be stored in the project repo):

example.png

But screenshots aren't text, preventing readers from copy/pasting the command in the screenshot. They're also a pain to create / edit / maintain, and are slower for browsers to load. The modern web uses text styles, not a bunch of rendered images of text.


While some markdown parsers support inline HTML styling, Github doesn't.

This doesn't work:

<span style="color: green"> Some green text </span>

This doesn't work:

<font color="green"> Some green text </font>

Below, you'll find clever answers with some creative hacks:

  • [Unicornist] Using emojis as colored bullets (????????????????) -- this is one of the better ideas, but is near the bottom, so consider giving it a vote. [Luke Hutchison] makes a similar suggestion, but Unicornist has a better selection of emoji bullets to choose from.

  • [AlecRust] Using a placeholder image service to render colored squares -- this predates the emoji solution, but solves a similar problem. It's more flexible on color, but less flexible on shape, and requires fetching an image from an external service, so really, it's just a screenshot that you can create programmatically.

  • [Vladimir Panteleev] using text rendering instructions in an SVG file, which is fewer bytes than a screenshot image, but has the same downside: no copy/paste support. Kind of neat though; makes me think I should play with SVG more.

  • [craigmichaelmartin] Abusing the DIFF color scheme to color entire lines in one of ~5 different colors -- caveat, requires including an extraneous initial character to trigger coloration (but incorporating that character into text like "-! Warning !-" is a really clever hack to hide it)

  • [ling] hacked up an entire text coloration service, although this seems more operationally fragile than just using pre-rendered screenshots.


There's still no solution for the general case of coloring arbitrary structured text

After upvoting this question and a few of the better answers, consider adding your +1 to the GitHub feature request: https://github.com/github/markup/issues/1440

12
If you're not able to color your text through markdown, would embedding a screenshot work?girasquid
YES. I thought of that just after I posted this question. I think screenshot might be my best fallback answer, though it's clearly not ideal.Dave Dopson
so it's not possible yet to add color to text in markdown file?Nam Nguyen
nope - and its july 2014 ffslfender6445

12 Answers

444
votes

It's worth mentioning that you can add some colour in a README using a placeholder image service. For example if you wanted to provide a list of colours for reference:

- ![#f03c15](https://via.placeholder.com/15/f03c15/000000?text=+) `#f03c15`
- ![#c5f015](https://via.placeholder.com/15/c5f015/000000?text=+) `#c5f015`
- ![#1589F0](https://via.placeholder.com/15/1589F0/000000?text=+) `#1589F0`

Produces:

  • #f03c15#f03c15
  • #c5f015#c5f015
  • #1589F0#1589F0
281
votes

You can use the diff language tag to generate some colored text:

```diff
- text in red
+ text in green
! text in orange
# text in gray
@@ text in purple (and bold)@@
```

However, it adds it as a new line starting with either - + ! # or starts and ends with @@

enter image description here

This issue was raised in github markup #369, but they haven't made any change in decision since then (2014).

93
votes

You cannot color plain text in a GitHub README.md file. You can however add color to code samples with the tags below.

To do this just add tags such as these samples to your README.md file:

```json
   // code for coloring
```
```html
   // code for coloring
```
```js
   // code for coloring
```
```css
   // code for coloring
```
// etc.

No "pre" or "code" tags needed.

This is covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

46
votes

Unfortunately, this is currently not possible.

The GitHub Markdown documentation has no mention of 'color', 'css', 'html', or 'style'.

While some Markdown processors (e.g. the one used in Ghost) allow for HTML, such as <span style="color:orange;">Word up</span>, GitHub's discards any HTML.

If it's imperative that you use color in your readme, your README.md could simply refer users to a README.html. The trade-off for this, of course, is accessibility.

28
votes

As an alternative to rendering a raster image, you can embed a SVG file:

<a><img src="http://dump.thecybershadow.net/6c736bfd11ded8cdc5e2bda009a6694a/colortext.svg"/></a>

You can then add color text to the SVG file as usual:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" 
     xmlns="http://www.w3.org/2000/svg"
     xmlns:xlink="http://www.w3.org/1999/xlink"
     width="100" height="50"
>
  <text font-size="16" x="10" y="20">
    <tspan fill="red">Hello</tspan>,
    <tspan fill="green">world</tspan>!
  </text>
</svg>

Unfortunately, even though you can select and copy text when you open the .svg file, the text is not selectable when the SVG image is embedded.

Demo: https://gist.github.com/CyberShadow/95621a949b07db295000

23
votes

I'm inclined to agree with Qwertman that it's not currently possible to specify color for text in GitHub markdown, at least not through HTML.

GitHub does allow some HTML elements and attributes, but only certain ones (see their documentation about their HTML sanitization). They do allow p and div tags, as well as color attribute. However, when I tried using them in a markdown document on GitHub, it didn't work. I tried the following (among other variations), and they didn't work:

  • <p style='color:red'>This is some red text.</p>
  • <font color="red">This is some text!</font>
  • These are <b style='color:red'>red words</b>.

As Qwertman suggested, if you really must use color you could do it in a README.html and refer them to it.

16
votes

These emoji characters are also useful if you are okay with this limited variety of colors and shapes (though they may look different in different OS/browsers), This is an alternative to AlecRust's answer which needs an external service that may go down someday, and with the idea of using emojis from Luke Hutchison's answer:

🔴🟠🟡🟢🔵🟣🟤⚫⚪🔘🛑⭕

🟥🟧🟨🟩🟦🟪🟫⬛⬜🔲🔳⏹☑✅❎

❤️🧡💛💚💜💙🤎🖤🤍♥️💔💖💘💝💗💓💟💕❣️♡

🔺🔻🔷🔶🔹🔸♦💠💎💧🧊

🏴🏳🚩🏁

◻️◼️◾️◽️▪️▫️

There are also many colored rectangle characters with alphanumeric/arrow/other-symbols that may work for you.


Example usage: This was my use-case that got solved by these emojis (which came to mind after reading the answers here)


Also, the following emojis are skin tone modifiers that have the skin colors inside this rectangular-ish shape only on some devices. For example, in Windows, they are not even colored. Don't use them! Because they shouldn't be alone, they're supposed to be used with other emojis to modify the output of their sibling emojis. and also they are rendered so much different in different os/version/browser/version combination when used alone.

🏿 🏾 🏽 🏼 🏻

13
votes

As of writing, Github Markdown renders color codes like `#ffffff` (note the backticks!) with a color preview. Just use a color code and surround it with backticks.

For example:

GitHub markdown with color codes

becomes

rendered GitHub markdown with color codes

8
votes

I added some color to a GitHub markup page using emoji Enicode chars, e.g. 💡 or 🛑 -- some emoji characters are colored in some browsers.

There are also some colored emoji alphabets: blood types 🅰️🅱️🅾️; parking sign 🅿️; Metro sign Ⓜ️; a few others with two or more letters, such as 🆗, and boxed digits such as 0️⃣. Flag emojis will show as letters (often colored) if the flag is not available: 🇯🇵 🇰🇷 🇩🇪 🇨🇳 🇺🇸 🇫🇷 🇪🇸 🇮🇹 🇷🇺 🇬🇧.

However, I don't think there is a complete colored alphabet defined in emoji.

4
votes

Based on @AlecRust idea, I did an implementation of png text service.

The demo is here:

http://lingtalfi.com/services/pngtext?color=cc0000&size=10&text=Hello%20World

There are four parameters:

  • text: the string to display
  • font: not use because I only have Arial.ttf anyway on this demo.
  • fontSize: an integer (defaults to 12)
  • color: a 6 chars hexadecimal code

Please do not use this service directly (except for testing), but use the class I created that provides the service:

https://github.com/lingtalfi/WebBox/blob/master/Image/PngTextUtil.php

class PngTextUtil
{
    /**
     * Displays a png text.
     *
     * Note: this method is meant to be used as a webservice.
     *
     * Options:
     * ------------
     * - font: string = arial/Arial.ttf
     *          The font to use.
     *          If the path starts with a slash, it's an absolute path to the font file.
     *          Else if the path doesn't start with a slash, it's a relative path to the font directory provided
     *          by this class (the WebBox/assets/fonts directory in this repository).
     * - fontSize: int = 12
     *          The font size.
     * - color: string = 000000
     *          The color of the text in hexadecimal format (6 chars).
     *          This can optionally be prefixed with a pound symbol (#).
     *
     *
     *
     *
     *
     *
     * @param string $text
     * @param array $options
     * @throws \Bat\Exception\BatException
     * @throws WebBoxException
     */
    public static function displayPngText(string $text, array $options = []): void
    {
        if (false === extension_loaded("gd")) {
            throw new WebBoxException("The gd extension is not loaded!");
        }
        header("Content-type: image/png");
        $font = $options['font'] ?? "arial/Arial.ttf";
        $fontsize = $options['fontSize'] ?? 12;
        $hexColor = $options['color'] ?? "000000";
        if ('/' !== substr($font, 0, 1)) {
            $fontDir = __DIR__ . "/../assets/fonts";
            $font = $fontDir . "/" . $font;
        }
        $rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
        //--------------------------------------------
        // GET THE TEXT BOX DIMENSIONS
        //--------------------------------------------
        $charWidth = $fontsize;
        $charFactor = 1;
        $textLen = mb_strlen($text);
        $imageWidth = $textLen * $charWidth * $charFactor;
        $imageHeight = $fontsize;
        $logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
        imagealphablending($logoimg, false);
        imagesavealpha($logoimg, true);
        $col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
        imagefill($logoimg, 0, 0, $col);
        $white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
        $x = 0;
        $y = $fontsize;
        $angle = 0;
        $bbox = imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
        $boxWidth = $bbox[4] - $bbox[0];
        $boxHeight = $bbox[7] - $bbox[1];
        imagedestroy($logoimg);
        //--------------------------------------------
        // CREATE THE PNG
        //--------------------------------------------
        $imageWidth = abs($boxWidth);
        $imageHeight = abs($boxHeight);
        $logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
        imagealphablending($logoimg, false);
        imagesavealpha($logoimg, true);
        $col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
        imagefill($logoimg, 0, 0, $col);
        $white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
        $x = 0;
        $y = $fontsize;
        $angle = 0;
        imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
        imagepng($logoimg); //save your image at new location $target
        imagedestroy($logoimg);
    }
}

Note: if you don't use the universe framework, you will need to replace this line:

$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);

With this code:

$rgbColors = sscanf($hexColor, "%02x%02x%02x");

In which case your hex color must be exactly 6 chars long (don't put the hash symbol (#) in front of it).

Note: in the end, I did not use this service, because I found that the font was ugly and worse: it was not possible to select the text. But for the sake of this discussion I thought this code was worth sharing...

-1
votes

Here is the code you can write color texts

<h3 style="color:#ff0000">Danger</h3>
-2
votes

<span color="red">red</span>

#!/bin/bash

# convert ansi-colored terminal output to github markdown

# to colorize text on github, we use <span color="red">red</span> etc
# depends on: aha, xclip
# license: CC0-1.0
# note: some tools may need other arguments than `--color=always`
# sample use: colors-to-github.sh diff a.txt b.txt

cmd="$1"
shift
(
    echo '<pre>'
    $cmd --color=always "$@" 2>&1 | aha --no-header
    echo '</pre>'
) \
| sed -E 's/<span style="[^"]*color:([^;"]+);"/<span color="\1"/g' \
| sed -E 's/ style="[^"]*"//g' \
| xclip -i -sel clipboard

trivial :)