Article

December 05, 2016

Override Bootstrap CSS for Pygments Syntax Highlighting

!important

This article was written in Markdown and then converted to html5 using Python's markdown package which in turn relies on Pygments for syntax highlighting. To install Pygments pip install Pygments and then generate css for it with:

pygmentize -S solarizeddark -f html -a .codehilite > ./static/css/codehilite-solarizeddark.css

and then include the css file in the head of your html/jinja2 template:

<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/codehilite-solarizeddark.css" rel="stylesheet">
<link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">

I was disappointed to see that bootstrap's styles were overriding some of the Pygments styles despite loading the Pygments css file after bootstrap.min.css. It turned out that the Pygments output was applying some of the styles to a <div> that wrapped the <pre> tags of the code block but not styling the <pre> tags themselves with color and background-color. Bootstrap was styling the <pre> tags, and since it was a more specific rule, bootstrap's styles won out.

CSS Priority Scores

Time to override bootstrap's styles. I wanted to do so cleanly, in a way that wouldn't be broken if I updated either bootstrap or Pygments in the future. Those requirements ruled out modifying the bootstrap or pygments css files themselves. By adding another stylsheet: compatability.css which contained:

/* fix bootstrap conflict with Pygments */
.codehilite pre { white-space: pre;
                  border-radius: inherit;
                  display: inherit;
                  background-color: inherit;
                  border: inherit;
                  color: inherit;
                }

/* fix conflict with other sytlesheets */
.codehilite .m { margin: inherit; }

I was able to override the bootstrap styles on the <pre> tag without touching either bootstrap or Pygments css files. Just be sure to add the include into the head of the html/template:

<link href="/static/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/css/compatability.css" rel="stylesheet">
<link href="/static/css/codehilite-solarizeddark.css" rel="stylesheet">
<link href="/static/font-awesome/css/font-awesome.css" rel="stylesheet">

Tags:

Comments: