Is putting a div inside an anchor ever correct?

前端 未结 14 2743
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:43

I\'ve heard that putting a block element inside a inline element is a HTML sin:

What we have here is a
相关标签:
14条回答
  • 2020-11-21 06:39

    If you're going to go to the effort of making <a> block, why not put <a> inside the div, being a block element it'll give you the same effect.

    0 讨论(0)
  • 2020-11-21 06:41

    Block level elements like <div> can be wrapped by <a> tags in HTML5. Although a <div> is considered to be a container/wrapper for flow content and <a>'s are considered flow content according to MDN. Semantically it may be better to create inline elements that act as block level elements.

    0 讨论(0)
  • 2020-11-21 06:43

    There's a DTD for HTML 4 at http://www.w3.org/TR/REC-html40/sgml/dtd.html . This DTD is the machine-processable form of the spec, with the limitation that a DTD governs XML and HTML 4, especially the "transient" flavor, permits a lot of things that are not "legal" XML. Still, I consider it comes close to codifying the intent of the specifiers.

    <!ELEMENT A - - (%inline;)* -(A)       -- anchor -->
    
    <!ENTITY % inline "#PCDATA | %fontstyle; | %phrase; | %special; | %formctrl;">
    
    <!ENTITY % fontstyle "TT | I | B | BIG | SMALL">
    
    <!ENTITY % phrase "EM | STRONG | DFN | CODE | SAMP | KBD | VAR | CITE | ABBR | ACRONYM" >
    
    <!ENTITY % special "A | IMG | OBJECT | BR | SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO">
    
    <!ENTITY % formctrl "INPUT | SELECT | TEXTAREA | LABEL | BUTTON">
    

    I would interpret the tags listed in this hierarchy to be the total of tags allowed.

    While the spec may say "inline elements," I'm pretty sure it's not intended that you can get around the intent by declaring the display type of a block element to be inline. Inline tags have different semantics no matter how you may abuse them.

    On the other hand, I find it intriguing that the inclusion of special seems to allow nesting A elements. There's probably some strong wording in the spec that disallows this even if it's XML-syntactically correct but I won't pursue this further as it's not the topic of the question.

    0 讨论(0)
  • 2020-11-21 06:44

    No it won't validate, but yes it generally will work in modern browsers. That being said, use a span inside your anchor, and set display: block on it as well, that will definitely work everywhere, and it will validate!

    0 讨论(0)
  • 2020-11-21 06:47

    It's wrong. Use a span.

    0 讨论(0)
  • 2020-11-21 06:48

    You can't put <div> inside <a> - it's not valid (X)HTML.

    Even though you style a span with display: block you still can't put block-level elements inside it: the (X)HTML still has to obey the (X)HTML DTD (whichever one you use), no matter how the CSS alters things.

    The browser will probably display it as you want, but that doesn't make it right.

    0 讨论(0)
提交回复
热议问题