Styling just comments inside a `pre` or `code` blo

2019-08-26 01:21发布

问题:

Is there a way to style comments inside a pre or code block (e.g. Ruby comments) using only CSS?

For example:

# I am a comment and should be lighter and italic
I = { :am => :normal_code, :and_want_no => :special_treatment }

I know you can use Javascript/jQuery to insert <span> elements in the right spots (like the <span>'s in the comment above provided by Stack Overflow) but can it be done with just CSS?

For background, I use a markdown renderer which outputs simple <pre> and <code> elements where necessary but without any hooks for indicating which language you're using and how to flag comments with <span> elements.

回答1:

This task can't be done with just CSS.

CSS works at the element level and it is not possible to "select into" general text - even trivially, much less applying some rules to parse language grammar.

As noted, and as seen by inspecting the SO code rendering such as the one in this post, one approach is to output spans with the appropriate CSS classes (which are the result of separate grammar processing) - then these individual spans, which can selected, are styled.



回答2:

  • a) What markdown renderer?
  • b) This can't be done with CSS with classes or ID's, as well as psuedo elements

I will expand further as you do.

The problem is, you can't exactly render comments with your provided method, as these are technically never rendered in the first place.

comments are meant to be non-runnable code to help for debugging. Trying to add comments or manipulate comments would be a security breach and would require actually inserting a file into your appreciable code.

As far as that would go? That would be a tricky scenario unless you had the same comment or multiple files available to do so. I would say to just import your file if necessary with a duplicate version with a commented version.