Are overlapping HTML formatting tags always a bad practice?

前端 未结 2 786
天涯浪人
天涯浪人 2021-01-23 03:35

Suppose I need to have a text with a bold and an italic part that overlap each other, like you see this sentence have.

Now, I know the proper w

相关标签:
2条回答
  • 2021-01-23 04:12

    As of HTML5, the procedure for dealing with these "overlapping tags" is standardized: https://html.spec.whatwg.org/multipage/syntax.html#adoption-agency-algorithm

    When parsing

    <div>I want this text to have both <b>bold <i>and</b> italic</i></div>
    

    we'll encounter the following step when we get to the </b> tag:

    1. If formatting element [here, the element started with <b>] is not the current node [here, the <i> element], this is a parse error. (But do not abort these steps.)

    The specification goes on to close the <i> and <b> and re-open a new <i> in this case. So while you do get a "parse error," this markup will still do what you want, according to the standard.

    So why might it be a bad practice?

    I'll try to stick with objective facts.

    This automatic fixup is limited to closing up to 8 levels of formatting tags (see step 3 in the algorithm). Because of that, it's not appropriate as a general technique.

    Also, elsewhere in the spec, https://html.spec.whatwg.org/multipage/syntax.html#parse-error

    ... user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

    Browser vendors are free to stop the parser if they don't want to deal with this situation.

    0 讨论(0)
  • 2021-01-23 04:21

    Combining i and b is totally fine, however, you need to make sure to nest them correctly.

    Wrong:

    I want this text to have both <b>bold <i>and</b> italic</i>
    

    Right: (depending on what you want to achieve, of course)

    I want this text to have both <b>bold <i>and</i></b> <i>italic</i>
    
    0 讨论(0)
提交回复
热议问题