CSS code highlighter - margin in pre code tag

Sourabh picture Sourabh · Apr 26, 2013 · Viewed 7.9k times · Source

Please look at this fiddle: Here

What I am looking for is a way to remove that extra space at top (the one between black circular 1 and top edge of pre tag) in first example and make it look like second one

The first example has some extra space above it (except the margin from strong elements), and I know that its because of the extra new-line after <pre><code> I didn't wanted to remove that extra newline as removing it makes the code look really unreadable, so I added this

pre > code > strong:first-of-type { margin-top: 10px; }

I thought it'll work but I forgot that I might have multiple strong tags in first line. Now I don't know what to do. Is there a work-around for my problem ?

Answer

Marc Audet picture Marc Audet · Apr 26, 2013

Try the following adjustment to your CSS:

pre > code {
    white-space: pre;
    margin-top: -1.00em;
    display: block;
}

You can also leave out:

pre > code > strong:first-of-type { margin-top: 10px; }  /** not needed **/

Fiddle: http://jsfiddle.net/audetwebdesign/WscKu/2/

Tested in Firefox on Windows 7, should work fine, basic CSS 2.1, nothing exotic.

How This Works

For visual formatting of your HTML source code, you have a line-feed after <pre><code>, which creates a single character line in your rendered content, which will be 1.00em tall.

You can compensate by setting the top margin to the <code> block to -1.00em. However, for top/bottom margins to work, you need to set display: block to the <code> element.