Is putting a div inside an anchor ever correct?

前端 未结 14 2742
孤独总比滥情好
孤独总比滥情好 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:49

    Depending on the version of HTML you're catering to:

    • HTML 5 states that the <a> element "may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links)".

    • HTML 4.01 specifies that <a> elements may only contain inline elements. A <div> is a block element, so it may not appear inside an <a>.

      Of course you are at liberty to style an inline element such that it appears to be a block, or indeed style a block so that it is rendered inline. The use of the terms inline and block in HTML refers to the relationship of the elements to the semantic structure of the document, whereas the same terms in CSS are related more to the visual styling of the elements. If you make inline elements display in a blocky manner, that's fine.

      However you should ensure that the structure of the document still makes sense when CSS is not present, for example when accessed via an assistive technology such as a screen reader - or indeed when examined by the mighty Googlebot.

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

    you can achieve this by adding "::before" Pseudo-element

    Pure CSS Trick ;)

    a:before{
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 1;
      pointer-events: auto;
      content: "";
      background-color: rgba(0,0,0,0);
    }
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="card" style="width: 18rem;">
      <img src="https://via.placeholder.com/250" class="card-img-top" alt="...">
      <div class="card-body">
        <h5 class="card-title">Card with stretched link</h5>
        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p>
        <a href="#" class="btn btn-primary stretched-link">Go somewhere</a>
      </div>
    </div>

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