开发者

HTML5/CSS: possible to define a <div> inside which all text is <code>?

开发者 https://www.devze.com 2023-02-04 20:25 出处:网络
I\'d like to define a CSS class that means all text inside is treated as though it were surrounded by the <co开发者_如何学运维de> tag. (In other words, it looks as though it is code: it doesn\'t

I'd like to define a CSS class that means all text inside is treated as though it were surrounded by the <co开发者_如何学运维de> tag. (In other words, it looks as though it is code: it doesn't need actually to have the <code> tags in the source.)

I guess the class should inherit from <code>.

Is this possible?


CSS is purely a presentational language -- it can make a DIV look as though it were a CODE element, but it can't actually add CODE tags. Depending on your requirement, this may or may not work for you. If you only want the looks, yes, you can use CSS. If you want the semantics of a CODE tag, no, CSS can't do it.

Edit: Since you just want the looks, you can do something like this:

div {
  display: inline;
  font-family: monospace;
}


Unfortunately, class is a misnomer in this case as CSS does not let you inherit element styles.

Your best bet is to set up a class with all of the appropriate attributes:

.code {
    font-face: Courier, "Courier New", monospace;
    white-space: pre-wrap;
    /* ... etc ... */
}

I have to ask though ... why not simply use the <code> tag?


If I understand your question correctly, you cannot accomplish this from CSS alone. You must actually have the code tag within your markup for the browser to treat it as code to display, and not code to parse.


Well I know you can do this with jQuery:

<script type="text/javascript">

    $('.myClass').each(function() {
        $(this).html('<code>' + $(this).html() + '</code>');
    });

</script>

Note: This has been typed in Safari, so I haven't tested it.

0

精彩评论

暂无评论...
验证码 换一张
取 消